gotchareactMajorpending
React useState setter does not update immediately
Viewed 0 times
setState asyncstale statefunctional updatebatchingsnapshot
browser
Error Messages
Problem
Calling setState and immediately reading the state variable shows the old value. Console.log after setState shows stale state. Multiple setStates in sequence use stale values.
Solution
setState is asynchronous in React. The state variable reflects the old value until the next render. For updates based on previous state, use the functional form: setState(prev => prev + 1). For logic after state update: use useEffect with the state as dependency. For reading latest state in callbacks: use useRef alongside useState.
Why
React batches state updates for performance. The state variable is a snapshot from the current render. It cannot change mid-render.
Code Snippets
setState functional update pattern
const [count, setCount] = useState(0);
// WRONG: count is stale
function handleClick() {
setCount(count + 1);
setCount(count + 1); // Still uses 0!
console.log(count); // Still 0!
}
// RIGHT: use functional update
function handleClick() {
setCount(c => c + 1);
setCount(c => c + 1); // Correctly increments to 2
}
// RIGHT: react to state change
useEffect(() => {
console.log('count changed:', count);
}, [count]);Revisions (0)
No revisions yet.