Skip to content

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.

15 min read0/4 questions

"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.

React
import { useState } from "react"; export default function App() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); console.log("right after setCount:", count); setTimeout(() => console.log("one second later:", count), 1000); } return <button onClick={handleClick}>Count: {count}</button>;}

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.

Predict the outputJavaScript

name is currently Ada, and the user clicks once. What is logged?

function handleClick() {
setName("Sam");
console.log(name);
}
Need a nudge? Hints walk you through it.

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?

React
import { useState } from "react"; export default function App() { const [count, setCount] = useState(0); return ( <div style={{ display: "flex", gap: 8, alignItems: "center" }}> <strong>{count}</strong> <button onClick={() => { setCount(count + 1); setCount(count + 1); setCount(count + 1); }}> +3 (buggy) </button> <button onClick={() => { setCount((c) => c + 1); setCount((c) => c + 1); setCount((c) => c + 1); }}> +3 (updater) </button> </div> );}

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.

React's update queue for one click
set 1
0
set 1
1
set 1
2
count = 0

Buggy button: count + 1 was evaluated with the snapshot count = 0, so the queue holds three plain values: replace with 1, three times.

1/6
Predict the outputJavaScript

count starts at 0. What does the screen show after one click?

function handleClick() {
setCount(count + 5);
setCount((c) => c + 1);
setCount(count + 2);
}
Need a nudge? Hints walk you through it.

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.

Mutating vs copying
const [user, setUser] = useState({ name: 'Ada', age: 36 })
NamesObjects in memoryuserobject{ name: 'Ada', age: 36 }

State points at one object.

1/3

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.

React
import { useState } from "react"; export default function App() { const [user, setUser] = useState({ name: "Ada", age: 36 }); return ( <div> <p> {user.name} is {user.age} </p> <button onClick={() => { user.age += 1; setUser(user); }} > Mutate </button>{" "} <button onClick={() => setUser({ ...user, age: user.age + 1 })}>Copy (works)</button> </div> );}

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.

GoalAvoid (mutates)Use (returns a new array)
Addpush, unshift[...arr, item], [item, ...arr]
Removesplice, pop, shiftarr.filter(x => x.id !== id)
Replace or edit onearr[i] = xarr.map(x => x.id === id ? { ...x, done: true } : x)
Sort or reversesort, reversearr.toSorted(), arr.toReversed(), or copy first
Insert in the middlesplice[...arr.slice(0, i), item, ...arr.slice(i)]
Match the pairs0/4 matched

Match each update to its immutable version.

Choose an item, then its match on the other side.
React
import { useState } from "react"; type Todo = { id: number; text: string; done: boolean };let nextId = 3; export default function App() { const [todos, setTodos] = useState<Todo[]>([ { id: 1, text: "Learn snapshots", done: true }, { id: 2, text: "Learn updaters", done: false }, ]); const add = () => { const id = nextId++; setTodos((t) => [...t, { id, text: `Todo #${id}`, done: false }]); }; const toggle = (id: number) => setTodos((t) => t.map((x) => (x.id === id ? { ...x, done: !x.done } : x))); const remove = (id: number) => setTodos((t) => t.filter((x) => x.id !== id)); return ( <div> <button onClick={add}>Add</button> <ul> {todos.map((t) => ( <li key={t.id}> <label style={{ textDecoration: t.done ? "line-through" : "none" }}> <input type="checkbox" checked={t.done} onChange={() => toggle(t.id)} /> {t.text} </label>{" "} <button onClick={() => remove(t.id)}>x</button> </li> ))} </ul> </div> );}

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.

Quick checkPick all that apply
Which updates are safe for items state? Pick all that apply.

None picked yet

Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

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: 0 to start.
  • Each click on +3 adds 3.
  • Reset sets the score back to 0.
React
import { useState } from "react"; export default function App() { const [score, setScore] = useState(0); function addThree() { setScore(score + 1); setScore(score + 1); setScore(score + 1); } return ( <div> <p>Score: {score}</p> <button onClick={addThree}>+3</button> <button onClick={() => setScore(0)}>Reset</button> </div> );}
ChallengeMedium

Fix the mutating cart

This cart mutates its state, so React never re-renders. Rewrite the three handlers to update state immutably.

  • Each <li> shows Name x{qty} followed by a +1 button and a Remove button.
  • +1 increases that item's quantity.
  • Remove deletes that item.
  • Add Milk adds { id: 3, name: "Milk", qty: 1 }, or, if Milk is already in the cart, increases its quantity.
  • A <p className="total"> shows Total items: N (the sum of all quantities).
Apple x1  [+1] [Remove]
Bread x2  [+1] [Remove]
Total items: 3        [Add Milk]
React
import { useState } from "react"; type Item = { id: number; name: string; qty: number }; export default function App() { const [cart, setCart] = useState<Item[]>([ { id: 1, name: "Apple", qty: 1 }, { id: 2, name: "Bread", qty: 2 }, ]); function increment(id: number) { const item = cart.find((i) => i.id === id)!; item.qty += 1; // mutation! setCart(cart); } function remove(id: number) { cart.splice( cart.findIndex((i) => i.id === id), 1, ); // mutation! setCart(cart); } function addMilk() { const milk = cart.find((i) => i.id === 3); if (milk) milk.qty += 1; // mutation! else cart.push({ id: 3, name: "Milk", qty: 1 }); // mutation! setCart(cart); } const total = cart.reduce((sum, i) => sum + i.qty, 0); return ( <div> <ul> {cart.map((item) => ( <li key={item.id}> <span> {item.name} x{item.qty} </span>{" "} <button onClick={() => increment(item.id)}>+1</button> <button onClick={() => remove(item.id)}>Remove</button> </li> ))} </ul> <p className="total">Total items: {total}</p> <button onClick={addMilk}>Add Milk</button> </div> );}
Key terms
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.