The useState Hook is one of the most fundamental hooks in React that allows functional components to manage state.
Before hooks, state management was only possible in class components, but useState made it available in functional components.
What is useState?
useState is a React Hook that lets you add state to functional components.
It returns a state variable and a function to update that state.
import { useState } from 'react';
const [count, setCount] = useState(0);Syntax of useState
The useState hook takes an initial value and returns an array with two elements.
The first is the current state value, and the second is a function to update it.
const [state, setState] = useState(initialValue);Basic Example
A simple counter example shows how useState works in practice.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}How State Updates Work
When you call the setter function, React schedules a re-render of the component with the updated state.
The UI automatically updates to reflect the new state value.
Multiple State Variables
You can use multiple useState hooks in a single component to manage different pieces of state.
function UserForm() {
const [name, setName] = useState('');
const [age, setAge] = useState(0);
return (
<div>
<input value={name} onChange={(e) => setName(e.target.value)} />
<input value={age} onChange={(e) => setAge(e.target.value)} />
</div>
);
}Updating State Based on Previous Value
When updating state based on the previous value, it is better to use a callback function.
This ensures you always get the latest state value.
setCount(prevCount => prevCount + 1);Rules of useState
Hooks must always be called at the top level of a React component.
They should not be called inside loops, conditions, or nested functions.
Common Mistakes
A common mistake is directly modifying state instead of using the setter function.
Another mistake is expecting state updates to happen immediately.
// Incorrect
count = count + 1;
// Correct
setCount(count + 1);useState with Objects
useState can also store objects, but you must remember to spread existing values when updating.
const [user, setUser] = useState({ name: '', age: 0 });
setUser(prev => ({ ...prev, name: 'Amit' }));Real-World Usage
useState is used in forms, toggles, counters, modals, filters, and dynamic UI components.
It is one of the most widely used hooks in React development.
Best Practices
Keep state minimal and avoid storing unnecessary data in state.
Split complex state into multiple useState hooks when needed.
Summary
useState is a powerful Hook that enables state management in functional React components.
Mastering useState is essential for building interactive and dynamic React applications.