Frontend · interactive
Hooks and stale closures
Each render of a React component is a fresh function call with its own props and state. A callback created during one render keeps seeing that render's values. An interval set up once, in the first render, sees count = 0 forever.
useEffect(() => {
const id = setInterval(() => setCount(count + 1), 1000);
return () => clearInterval(id);
}, []); // runs once| after | callback sees count | count becomes |
|---|---|---|
| 1 s | 0 | 1 |
| 2 s | 0 | 1 |
| 3 s | 0 | 1 |
| 4 s | 0 | 1 |
| 5 s | 0 | 1 |
intervals created: 1
The effect ran once, so its callback closed over the first render, where count is 0. Every tick sets count to 0 + 1. The counter is stuck at 1.
Version
Step 1 of 4 · read left to right
In production
Tools and technologies
Every React developer hits this with effects and intervals.
Not tied to one language — use these names when you search docs or design a system.