Reading State Right After Setting It
What you'll learn: Why trying to read state immediately after calling setState doesn't give you the updated value.
You've learned that state updates are scheduled, not applied instantly. This creates a common beginner trap: calling setState, then immediately reading that state variable and expecting to see the new value.
The Problem
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log(count); // Still shows 0, not 1!
}
return <button onClick={handleClick}>Count: {count}</button>;
}
When you click the button, console.log(count) prints the old value. Why? Because setCount only schedules a re-render—it doesn't instantly change the count variable you're holding in this render.
The Mental Model
Think of state like a photo. When your component function runs, it takes a "snapshot" of the current state values. Calling setState doesn't alter the photo you're already holding—it tells React to take a new photo next time, with updated values.
The count variable in your current execution of handleClick is frozen at 0. Even after scheduling an update, that variable doesn't magically change mid-function.
What Actually Happens
setCount(count + 1)schedules a re-render with the new value- Your current function continues with the old
count - After the function finishes, React re-renders
- The next render gets the updated value
If you need the new value immediately within your logic, calculate it yourself: const newCount = count + 1, then use newCount in both setCount and any subsequent code.
Key Takeaway: State variables are snapshots—they don't update mid-render. setState schedules a future re-render with new values, but the current render keeps its frozen snapshot.