Sub topic 2
Why mutating state does not work
This chapter assumes you know JavaScript objects and arrays, the spread operator, useState, and how to handle events in React. It explains why changing a state object in place fails. The next chapters cover the copy patterns that fix it.
State is a snapshot
Each time React renders a component, it calls your function and gives it the state values for that render. Those values are a snapshot. The JSX you return, and every event handler defined in that render, see exactly those values.
A setter such as setPerson does not edit the snapshot. It asks React to schedule a new render with a new value. The current render's variables never change.
Mutating state means changing an existing object in place, for example person.firstName = 'Grace'. This changes the object that the current snapshot points to, and it does so without telling React.
A bug you can run
This component keeps a score in an object. The button mutates the object and then passes the same object to the setter.
import { useState } from 'react';
export default function Scoreboard() {
const [score, setScore] = useState({ points: 0 });
const [clicks, setClicks] = useState(0);
function handleAddPoint() {
score.points += 1; // mutation
setScore(score); // same object as before
}
return (
<div>
<p>Points: {score.points}</p>
<button onClick={handleAddPoint}>Add point</button>
<p>Unrelated clicks: {clicks}</p>
<button onClick={() => setClicks(clicks + 1)}>Click me</button>
</div>
);
}Click "Add point" several times. The screen still says Points: 0. Now click "Click me". The points display jumps to the real total.
Both symptoms have the same cause. The object really did change, so the next render that happens for any reason reads the new value. But the first render was never requested.
How React decides whether to render
When you call a setter, React compares the new value with the current one using Object.is. For objects and arrays, this compares references, not contents. If the two values are the same reference, React treats the update as a no-op and skips the re-render.
In the example, score and the argument to setScore(score) are the same object. Object.is(score, score) is true, so React does nothing.
const a = { points: 0 };
a.points = 5;
console.log(Object.is(a, a)); // true: same reference, "no change"
console.log(Object.is(a, { ...a })); // false: new reference, "changed"React does not deep-compare your data. Checking every nested property on every update would be slow, so it relies on one rule: a new value must be a new reference.
The fix, in one step
Create a new object that holds the changed value, and pass that to the setter.
function handleAddPoint() {
setScore({ ...score, points: score.points + 1 });
}{ ...score, points: ... } builds a new object, so Object.is returns false and React renders. The next chapters cover this pattern in detail, including nested data and arrays.
Mutation breaks the snapshot
Skipped renders are only the first problem. Mutation also breaks the rule that a handler sees the values from its own render.
import { useState } from 'react';
export default function Greeting() {
const [person, setPerson] = useState({ firstName: 'Ada' });
function handleClick() {
setTimeout(() => {
console.log('Timer sees:', person.firstName);
}, 2000);
person.firstName = 'Grace'; // mutation
setPerson(person);
}
return <button onClick={handleClick}>Rename</button>;
}The timer callback closes over the person variable from the render in which the click happened. You would expect it to log Ada, because that is the snapshot the handler was created in. With mutation, it logs Grace, because the snapshot's own object was edited in place.
Replace the mutation with setPerson({ ...person, firstName: 'Grace' }) and the callback logs Ada. The old object is untouched, and the new render gets a new object.
Where else reference checks matter
React is not the only code that compares references. Several features depend on it, and mutation silently defeats each one.
| Feature | What it compares | What goes wrong with mutation |
|---|---|---|
| `useState` setter | New value against current value | The update is skipped, so the screen is stale |
| `React.memo` | Each prop against its previous value | A memoized child does not re-render when its object prop is edited in place |
| `useEffect`, `useMemo`, `useCallback` dependency arrays | Each dependency against its previous value | Effects do not re-run and cached values go stale |
| Context value | Provider value against the previous value | Consumers are not notified |
| Developer tools and debugging | Earlier states against later states | The earlier state is gone, so you cannot see what changed |
The dependency-array case is easy to miss. This effect never re-runs after a mutation, because filters has the same reference every time:
import { useEffect, useState } from 'react';
export default function Results() {
const [filters, setFilters] = useState({ query: '' });
useEffect(() => {
console.log('Searching for', filters.query);
}, [filters]);
function handleChange(e) {
filters.query = e.target.value; // effect will not re-run
setFilters(filters);
}
return <input onChange={handleChange} />;
}Mutation can appear to work
Some mutations seem fine. If you mutate an object and then call another setter that triggers a render, the new value shows up, as in the scoreboard example. A mutation can also seem to work in a small component that re-renders often.
These cases are accidents. The code works only while some other state change happens to cause a render. Later someone wraps a child in React.memo, moves the update into an effect, or removes the unrelated state, and the screen stops updating. Treat any mutation of state as a bug, even when it seems to work today.
Mutating during render and in updaters
Mutating state during rendering is a related mistake. Your component function should compute its output from its inputs and should not change them. In development, React Strict Mode runs components and updater functions twice to expose such impurities. If your code mutates state while rendering, the double call makes the problem visible, for example by adding an item twice.
// Wrong: mutates state while computing the next value
setTodos((prev) => {
prev.push({ id: nextId++, title: 'Learn', done: false });
return prev; // same reference, and Strict Mode would push twice
});Returning prev also fails the reference check. The correct form returns a new array, [...prev, newTodo]. Updater functions get their own chapter later.
What counts as mutation
You mutate when you change an object or array that state already holds. Both are mutations:
- Assigning to a property:
person.name = 'Grace'orperson.address.city = 'Paris'. - Calling a mutating method on the state array:
items.push(x),items.splice(0, 1),items.sort(),items.reverse().
Reassigning a local variable that you created yourself is fine. A new object you built inside the handler and have not yet passed to React is also yours to change. Rule of thumb: never change something that came from useState or from props.
function handleAdd() {
const next = { points: score.points }; // our own new object
next.points += 1; // fine: it is not state yet
setScore(next); // new reference, so React renders
}This works, but it is verbose. Spread syntax, covered next, is shorter.
Common mistakes
- Calling
setX(x)after changingx. Passing the same reference is a no-op even if the contents differ. - Believing
useStatesetters work likeObject.assign. They replace the value and do not merge it. - Mutating a nested object and copying only the top level. The top-level reference changes, but the nested one is shared with the old snapshot. The shallow-copy chapter covers this.
- Treating
constas protection.const [person, setPerson] = useState(...)stops you reassigningperson, but it does not stopperson.name = 'x'.
Exercise
A component holds const [cart, setCart] = useState({ items: 2 }). The handler does cart.items = cart.items + 1; setCart(cart);. The screen shows no change, but a later click on an unrelated button shows 3. Explain both observations and write the corrected handler.
Show answer
The handler mutates the existing object and passes the same reference to the setter. React compares the new value with the current one using Object.is, finds the same reference, and skips the render, so the screen stays stale. The object did change in memory, so the next render triggered by the unrelated button reads items as 3. The fix is to create a new object: setCart({ ...cart, items: cart.items + 1 });.
Exercise
Name two React features other than the state setter that stop working correctly when you mutate an object in place, and say why.
Show answer
Any two of these. React.memo skips re-rendering a child whose props are the same references as before, so an edited object prop does not update the child. Dependency arrays of useEffect, useMemo, and useCallback compare entries by reference, so the effect does not re-run and the memoized value goes stale. A context provider does not notify consumers when its value keeps the same reference. All of them compare references, and an in-place mutation does not change the reference.