Reading State After setState
What you'll learn: Why console.log(count) right after setCount(count + 1) still shows the old value.
The Confusing Surprise
You've just learned that state updates are asynchronous. Here's where that really trips people up:
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log(count); // Still shows 0, not 1! 😵
}
Even though you called setCount, the count variable in your current function doesn't change. It's still the value from when the function started running.
Why This Happens
Think of it like mailing a letter to update your address. The moment you drop the letter in the mailbox, your driver's license doesn't magically update. You have to wait for the system to process it.
When you call setCount(count + 1), you're scheduling a state update. React will:
- Queue your update
- Re-render your component
- Call your function again with the new state value
But right now, in this function call, count is just a regular number variable. It won't suddenly become a different number mid-function.
The Solution
If you need to use the new value immediately, just use the value you calculated:
function handleClick() {
const newCount = count + 1;
setCount(newCount);
console.log(newCount); // This works!
}
Or realize you don't need to log state at all—it'll be available on the next render.
Key Takeaway: State variables don't update mid-function after calling their setter. The new value appears on the next render when your component runs again.