Find: Stale Closure in setInterval
Find the Mistake Medium
Question
What is wrong with this useEffect?
Code
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1);
}, 1000);
return () => clearInterval(id);
}, []);
Hint
What value of count does the interval callback see?
Explanation
The interval callback captures count from the first render (always 0), so count + 1 is always 1. This is a stale closure. The fix is to use the updater function: setCount(prev => prev + 1); which always gets the latest value.
Related Resources
Related Lessons
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.