Why State Updates Don't Appear Immediately
What you'll learn: Why calling setState doesn't instantly change the value you read from your state variable.
The Asynchronous-Feeling Puzzle
When you call setState, you might expect the state variable to update right away. But if you try to read it immediately after, you'll see the old value:
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log(count); // Still 0! Not 1!
}
This feels asynchronous, but it's not about network delays or timers. It's about React's three-phase model.
The Three-Phase Explanation
When you call setState inside an event handler:
- Render Phase: React schedules a re-render but doesn't execute it yet. Your current function keeps running with the old state snapshot.
- Commit Phase: After your function finishes, React re-renders the component with the new state and updates the DOM.
- Effects Phase: Any effects run after the paint.
The key insight: setState is a request to re-render later, not an immediate mutation. Your component function sees state as a constant snapshot for that render. The new value only exists in the next render.
The Snapshot Analogy
Think of each render as a photograph. When you call setCount(1), you're not changing the photo in your hand—you're scheduling a new photo to be taken. The current photo (render) still shows count: 0.
Key Takeaway: State updates don't appear immediately because React batches them and processes them in the next render phase, keeping each render's state snapshot consistent throughout the function execution.