Closures Capture State Snapshots
You'll learn: Why each render creates a frozen snapshot of state values that closures "remember" forever.
The Core Idea
Every time your component renders, React creates a new function body with fresh variables. Any closures you create during that render—like event handlers or async callbacks—capture the state values from that specific render. They don't magically update when state changes later.
Think of it like taking a photograph: when you snap a picture at 3pm, that photo forever shows 3pm. It doesn't update to 4pm when the clock changes. Similarly, a function created during render #1 forever "sees" the state values from render #1, even after render #2 happens with new values.
Why This Matters
When you write an event handler or setTimeout callback, it captures the state value at the moment the function was created. If state changes and a re-render occurs, that old function still has the old value:
function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
setTimeout(() => {
console.log(count); // Captures count from THIS render
}, 3000);
};
return <button onClick={handleClick}>Log: {count}</button>;
}
If count is 0 when you click, then you increment it to 5, the setTimeout will still log 0 after 3 seconds—it captured the snapshot from when you clicked.
The Solution
Use functional updates when you need the current value:
setTimeout(() => {
setCount(prev => prev + 1); // Reads fresh value
}, 3000);
Key Takeaway: Every render creates a new snapshot of state, and closures freeze those values at render-time. Old functions see old values, even after new renders happen.