Can you access the updated state immediately after calling setState?
No — state updates in React are asynchronous and batched. Calling setState schedules an update; the state variable in your current function still holds the snapshot value from the current render.
You cannot read the new value directly after calling the setter in the same synchronous block. The updated value is only available in the next render.
How to work around it:
- Use the functional update form
setState(prev => ...)when the next state depends on the current - Use a
refalongside state if you need the value synchronously (rare) - Use
useEffectwith the state variable as a dependency to react to changes
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log(count); // ❌ Still logs the OLD value — state is a snapshot
setCount(count + 1); // ❌ Also adds 1, not 2 — both reads use same snapshot
}
function handleClickFixed() {
// ✅ Functional update: React applies these sequentially
setCount(prev => prev + 1);
setCount(prev => prev + 1); // Count goes up by 2 correctly
}
return <button onClick={handleClick}>{count}</button>;
}
// ✅ React to state changes with useEffect
useEffect(() => {
console.log('count changed to:', count); // Runs after render with new value
}, [count]);