Why You Can't Rely on State Mid-Render
What you'll learn: State represents a snapshot from when the render started—it won't change partway through, even if you call the setter.
The Core Idea
When React renders your component, it takes a "snapshot" of your state at that moment. Throughout that entire render, state values remain frozen. Even if you call setState during the render process, the current render will continue using the old value. The new value only appears in the next render.
Think of it like taking a photograph. Once you snap the picture, people can move around all they want—the photo itself doesn't change. You need to take a new photo to capture their new positions.
Why This Matters
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
// count is STILL 0 here, not 1
console.log(count); // logs 0
setCount(count + 1); // uses 0 again, sets to 1 (not 2!)
}
return <button onClick={handleClick}>{count}</button>;
}
In this example, both setCount calls see count as 0 because that's the snapshot from the current render. You might expect the count to become 2, but it only becomes 1.
The state variable doesn't "watch" for changes—it's just a regular JavaScript variable that holds a value for this render. Once React starts rendering your component, that value is locked in until the next render begins.
The Snapshot Analogy
Each render gets its own snapshot of state values, like frames in a movie. Each frame is complete and unchanging. The next frame might look different, but it's a separate picture.
Key Takeaway: State is a snapshot—its value stays constant throughout the entire render, regardless of setter calls. Changes only appear in the next render.