How to manage local state with useState in React
· Category: React
Short answer
useState is a React Hook that lets functional components hold and update local state. It returns the current state value and a setter function.
Steps
- Import
useStatefrom React. - Call it with an initial value:
const [count, setCount] = useState(0). - Read the state directly.
- Update it with the setter, using a functional updater when the new state depends on the previous state.
Example
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount((c) => c + 1)}>+</button>
</div>
);
}
Common issues
- State updates are batched and asynchronous; do not read
countimmediately aftersetCountand expect it to reflect the new value. - Objects and arrays must be replaced, not mutated. Use the spread operator or a library like Immer.