What is useState Hook in React?

This article provides a quick overview of the useState hook in React, explaining its purpose, syntax, and practical application. By the end of this guide, you will understand how to manage state in functional components, write a basic stateful component, and follow best practices for state updates.

Understanding State in React

In React, “state” refers to data or properties that can change over time and affect how a component renders. Before React 16.8, state could only be managed inside class components. The introduction of Hooks, specifically the useState hook, enabled developers to use local state inside functional components, making code cleaner and easier to maintain.

Syntax of useState

To use useState, you must first import it from the React library. The hook is a function that takes one argument—the initial state—and returns an array containing two elements:

  1. The current state value: The variable holding the active state.
  2. The state updater function: A function used to update the state value and trigger a re-render of the component.

Here is the standard syntax using array destructuring:

import React, { useState } from 'react';

const [state, setState] = useState(initialValue);

Practical Example: A Simple Counter

Below is a practical example of a counter component. It demonstrates how to initialize state, display it, and update it using a button click.

import React, { useState } from 'react';

function Counter() {
  // Declare a state variable named "count", initialized to 0
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Current Count: {count}</p>
      {/* Update the state when the button is clicked */}
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}

export default Counter;

How the Example Works:

Key Rules and Best Practices

To ensure your application runs smoothly, keep these key concepts in mind when using the useState hook: