useState stale closure in event handler
Quick summary
Your event handler reads a stale state value from the render in which it was created — the closure captured the old state, not the current one.
Why this happens
The event handler was defined in a render cycle and captured the state value from that render, not the latest
You used useState value directly in a setTimeout or setInterval callback that was set up in an earlier render
The handler is memoized with useCallback but its dependency array does not include the state it reads
Minimal example
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1); // stale closure!
}, 1000);
return () => clearInterval(id);
}, []); // count not in deps
}function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(prev => prev + 1); // functional update
}, 1000);
return () => clearInterval(id);
}, []); // no deps needed
}Using a functional update (prev => prev + 1) always reads the latest state value, avoiding the stale closure problem entirely.
How to diagnose
Log the state value inside the handler to confirm it shows the old value, not the current one
Check whether the handler is recreated on every render or memoized with missing dependencies
Use a ref to track the latest state and compare with the captured value to detect staleness
How to fix
Use a functional state update: setCount(prev => prev + 1) instead of setCount(count + 1) to always use the latest value
Add the state variable to the dependency array of useCallback or useEffect so the handler is recreated with fresh values
Use a ref (useRef) to store the latest state and read ref.current in the handler to always access the current value
How to prevent
Always use functional updates for state that depends on the previous value: setX(prev => newValue)
Include all variables the handler reads in the dependency array of useCallback or useEffect