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:
- The current state value: The variable holding the active state.
- 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:
- Initialization:
useState(0)sets the initial value ofcountto0. - Rendering:
{count}displays the current value on the screen. - Updating: Clicking the button triggers
setCount(count + 1). React updates thecountvariable and automatically re-renders theCountercomponent to display the new value.
Key Rules and Best Practices
To ensure your application runs smoothly, keep these key concepts in
mind when using the useState hook:
Do Not Modify State Directly: Never mutate state variables directly (e.g.,
count = count + 1). Always use the updater function (setCount) so React knows to trigger a re-render.Functional Updates: If your new state depends on the previous state, pass a function to the state updater. This prevents bugs caused by asynchronous state updates:
setCount(prevCount => prevCount + 1);Top-Level Usage Only: Only call hooks at the very top level of your functional components. Do not call them inside loops, conditions, or nested functions.