A common point of confusion is why console.log shows the old value right after setState.
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
console.log(count); // Still 0!
}
The Mental Model
State is not a variable you can mutate. It’s a snapshot for the current render.
- Trigger: You click logic.
- Schedule:
setCount(0 + 1)tells React “In the next render,countshould be 1”. - Render: React calls your component function again. This time
useState(0)returns1. - Paint: The UI updates.
Think of functionality inside your component as closing over the state of that specific render.