Lesson 8 of 37State
State as a Snapshot
Predict exactly what state holds during a render, use updater functions, and update objects and arrays immutably.
"I called setCount but count is still the old value!" is the most common React question on the internet. The answer is one mental model: each render is a snapshot, and state inside it never changes. Once you have that model, batching, updater functions and immutable updates all follow, and you will spot these bugs in code review instantly.
Each render sees fixed values
When React calls your component, it hands you the state for that render. Your JSX, and every event handler created during that render, see those values. Calling a setter does not change the variable you already have. It asks React for a new render with a new value.
Click the button and read the log.
Both logs show the old number, even the delayed one. count is a const from the render in which the click happened. Think of it as a photo: the next render takes a new photo, but the handler is still holding the old one.
name is currently Ada, and the user clicks once. What is logged?
function handleClick() {
setName("Sam");
console.log(name);
}Batching: one re-render per event
If every setter call re-rendered immediately, a handler that updates three pieces of state would render three times. Instead React batches: it collects all the state updates from one event and does a single re-render after your handler finishes. Since React 18 this also applies inside timeouts, promises and native event handlers.
Batching plus snapshots explains a famous puzzle. What happens after one click here?
The buggy button adds 1. In that render count is 0, so it calls setCount(1) three times. The second button passes an updater function, and React runs each one on the result of the previous one.
Buggy button: count + 1 was evaluated with the snapshot count = 0, so the queue holds three plain values: replace with 1, three times.
count starts at 0. What does the screen show after one click?
function handleClick() {
setCount(count + 5);
setCount((c) => c + 1);
setCount(count + 2);
}Rule of thumb: when the new state depends on the old state, use the updater form setX(prev => ...). It is always correct, even with several updates in a row or in async code. When you are setting a value that does not depend on the previous one (setName(e.target.value)), the plain form is fine.
Updating objects without mutating them
State can hold objects and arrays, but you must treat them as read-only. To change one, create a new object with the change and pass that to the setter.
Why? To decide whether to re-render, React compares the old and new state with Object.is. If you mutate the existing object and pass it back, it is the same reference, so React concludes nothing changed and skips the render.
State points at one object.
The spread syntax { ...user, age: 37 } copies every property and then overrides age. For nested objects, copy each level you change:
setUser({
...user,
address: { ...user.address, city: "Lisbon" },
});Here it is live. The first button mutates; the second copies.
Press Mutate a few times first: the screen does not change. Then press Copy. The age jumps by more than one, because the mutations did change the object; React just was not told. That hidden, out-of-sync data is why mutation bugs are so confusing.
Updating arrays without mutating them
The same rule applies to arrays. Avoid the methods that change an array in place, and use the ones that return a new array.
| Goal | Avoid (mutates) | Use (returns a new array) |
|---|---|---|
| Add | push, unshift | [...arr, item], [item, ...arr] |
| Remove | splice, pop, shift | arr.filter(x => x.id !== id) |
| Replace or edit one | arr[i] = x | arr.map(x => x.id === id ? { ...x, done: true } : x) |
| Sort or reverse | sort, reverse | arr.toSorted(), arr.toReversed(), or copy first |
| Insert in the middle | splice | [...arr.slice(0, i), item, ...arr.slice(i)] |
Match each update to its immutable version.
Note that map with { ...x, done: !x.done } copies the one item that changes. Writing x.done = !x.done inside map would still mutate the old object, even though the array itself is new.
items state? Pick all that apply.None picked yet
Fix the +3 button
The +3 button is supposed to add 3, but it only adds 1. Fix it without changing it to a single setScore(score + 3) call: keep three separate updates (imagine each one is a separate bonus that might be skipped later).
Score: 0to start.- Each click on
+3adds 3. Resetsets the score back to 0.
Fix the mutating cart
This cart mutates its state, so React never re-renders. Rewrite the three handlers to update state immutably.
- Each
<li>showsName x{qty}followed by a+1button and aRemovebutton. +1increases that item's quantity.Removedeletes that item.Add Milkadds{ id: 3, name: "Milk", qty: 1 }, or, if Milk is already in the cart, increases its quantity.- A
<p className="total">showsTotal items: N(the sum of all quantities).
Apple x1 [+1] [Remove]
Bread x2 [+1] [Remove]
Total items: 3 [Add Milk]- snapshot
- The fixed state values of one render. Handlers created in that render keep seeing those values.
- batching
- React groups all state updates from one event into a single re-render.
- updater function
setX(prev => next): React passes the latest queued value, so several updates in a row stack correctly.- immutable update
- Creating a new object or array with the change instead of modifying the existing one.
- Object.is
- How React compares old and new state. The same reference means no change, so mutation can skip re-renders.