The Classic Stale Closure Bug
You'll learn why forgetting to include state or props in your dependency array causes your effect to see outdated values.
The Core Problem
When you create an effect, JavaScript "captures" the values of variables from the render where the effect was created. If you omit state or props from the dependency array, your effect won't re-run when those values change—it keeps using the old captured values forever.
This is the classic stale closure bug: your effect "closes over" stale (outdated) values because it never gets recreated with fresh ones.
How It Happens
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
console.log(count); // Always logs 0!
}, 1000);
return () => clearInterval(interval);
}, []); // Missing count!
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}
The effect runs once on mount (empty array). The setInterval callback captures count from that first render—which is 0. Even as count updates to 1, 2, 3, the interval keeps logging 0 because it's stuck with that stale value.
The Fix
Include count in the dependency array:
useEffect(() => {
const interval = setInterval(() => {
console.log(count); // Now logs current count
}, 1000);
return () => clearInterval(interval);
}, [count]); // Effect recreates when count changes
Now the effect cleans up and re-runs whenever count changes, capturing the fresh value each time.
Key Takeaway: Omitting dependencies from the array doesn't make your effect more efficient—it makes it wrong. Your effect sees frozen, outdated values, causing bugs that are hard to trace.