Bug: Stale closure — event handler uses old state value
Error message
Event handler captures a stale state value
Quick summary
An event handler created in a previous render captures the state value from that render, not the current one.
Why this happens
Event handler captures state from the render it was created in
useEffect with empty deps captures initial state
setTimeout/setInterval callback captures old state
Minimal example
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1); // count is always 0!
}, 1000);
return () => clearInterval(id);
}, []); // count not in depsconst [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(prev => prev + 1); // Uses latest value
}, 1000);
return () => clearInterval(id);
}, []);The updater function prev => prev + 1 always receives the latest state, avoiding the stale closure problem.
How to diagnose
Log the state value inside the handler to see if it's stale
Check if the handler is memoized with stale dependencies
Look for closures created in effects with incomplete deps
How to fix
Use the updater function form:
setCount(prev => prev + 1)Add the state to the dependency array of useEffect/useCallback
Use a ref to hold the latest value if you can't add it to deps
How to prevent
Use updater functions for state that depends on previous values
Always include all used values in dependency arrays
Use useRef for values that need to be read in stale closures
Related Resources
Related Glossary
Related Lessons
- useEffect
Learn to avoid stale closures.