How to Use the useState Hook in React
This article provides a straightforward guide on how to implement the
useState Hook in React. You will learn the fundamental
syntax of useState, how to declare state variables, and how
to update them in functional components using a practical step-by-step
code example.
Understanding the useState Hook
The useState Hook is a built-in React function that
allows you to add state to functional components. Before hooks were
introduced, state management required writing class components.
To use useState, you must first import it at the top of
your React file:
import React, { useState } from 'react';The Syntax of useState
The useState Hook is called directly inside your
component. It accepts a single argument, which is the initial state
value, and returns an array with exactly two values:
- The current state value: The variable representing the active state.
- The state setter function: A function used to update the state variable and trigger a component re-render.
We use JavaScript array destructuring to assign names to these two values:
const [state, setState] = useState(initialValue);Step-by-Step Implementation
Here is a complete, real-world example of how to implement
useState to build a simple counter component.
1. Initialize the State
Inside the component, initialize a state variable called
count with a starting value of 0.
const [count, setCount] = useState(0);2. Create an Update Function
To change the state, call the setter function setCount
and pass the new value.
const increment = () => {
setCount(count + 1);
};3. Render the State and Bind the Event
Display the current count value in the JSX and attach
the increment function to a button’s onClick
event handler.
Complete Code Example
import React, { useState } from 'react';
function Counter() {
// 1. Declare the state variable "count" and its setter "setCount"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
{/* 2. Update the state on button click */}
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default Counter;Key Rules to Remember
- Call hooks at the top level: Do not call
useStateinside loops, conditions, or nested functions. - Only call hooks from React functions: Use hooks inside React functional components or custom hooks, not regular JavaScript functions.
- State updates trigger re-renders: Every time you
call the setter function (e.g.,
setCount), React re-renders the component to display the updated data in the UI.