Stale State in setTimeout and setInterval
You'll learn: Why timers like setTimeout and setInterval often reference outdated state values and how to recognize the problem.
The Invisible Time Capsule
When you create a setTimeout or setInterval inside a React component, that timer creates a closure over the current state at that exact moment. It's like taking a snapshot of state and sealing it in a time capsule. When the timer fires seconds (or minutes) later, it still references that old snapshot—even if the state has changed multiple times since then.
const [count, setCount] = useState(0);
function handleClick() {
setTimeout(() => {
console.log(count); // Always logs 0, even if count changed!
}, 3000);
setCount(count + 1); // User sees 1, but timer captured 0
}
In this example, the timer captures count when it's 0. Three seconds later, even if you've clicked the button ten times and count is now 10, the timer still logs 0. The callback function "remembers" the old value.
Why This Happens
Each render creates a new version of your component function with fresh variable bindings. When you schedule a timer, its callback closes over that render's variables. The timer doesn't magically update to use newer state—it's permanently bound to the stale values.
This is the same closure trap you've seen with direct state updates, but it's especially sneaky with timers because the delay makes the staleness obvious and problematic.
Common Symptom
You increment state in a timer, but it always jumps to the same number instead of incrementing properly. That's stale state in action.
Key Takeaway: Timers capture state at creation time and always reference those stale values unless you use functional updates (setState(prev => ...)) or other patterns to work around closures.