Sub topic 8
Why State Must Not Be Mutated
Prerequisites
This chapter assumes you can declare state with useState, update it from event handlers, and use object spread syntax. It builds on the earlier chapters about state snapshots and re-rendering.
What mutation means
Mutation means changing an existing object or array in place, for example person.name = 'Grace' or items.push(x). Numbers, strings, and booleans cannot be mutated, so you can only replace them. Objects and arrays can be mutated, so the rule matters for them.
React's rule is to treat state as read-only. To change an object or array, build a new one and pass it to the setter.
What goes wrong
This component mutates its state and then passes the same object to the setter.
import { useState } from 'react';
function BrokenProfile() {
const [person, setPerson] = useState({ name: 'Ada' });
function rename() {
person.name = 'Grace';
setPerson(person);
}
return (
<>
<p>{person.name}</p>
<button onClick={rename}>Rename</button>
</>
);
}Clicking the button does not update the screen. React compares the new value with the current one using Object.is. Both values are the same object reference, so React decides nothing changed and skips the re-render.
The fix is to pass a new object:
setPerson({ ...person, name: 'Grace' });The spread creates a new object with the old properties, and name overrides the old value. The reference differs, so React re-renders.
Other reasons the rule exists
- Snapshots stay intact. Each render's handlers close over that render's state. Mutating the object changes what those older closures see, which breaks the snapshot model.
- Memoization depends on references.
React.memo,useMemo, and dependency arrays compare values by reference. A mutated object keeps its reference, so they can skip work they should have done. - Bugs hide. A mutation may appear to work when an unrelated update triggers a re-render. The bug then shows up only in some situations.
Copy along the path, not just the top
Spread makes a shallow copy. It copies the top-level properties, but nested objects are still shared with the old state. To update a nested value, copy every level on the way down.
setPerson({
...person,
address: { ...person.address, city: 'Paris' },
});Writing person.address.city = 'Paris' first and then spreading person would still mutate the old state, because address is shared.
Quick reference
| Goal | Mutating (avoid) | Non-mutating |
|---|---|---|
| Add to array | `push`, `unshift` | `[...items, x]` |
| Remove from array | `splice`, `pop` | `filter` |
| Replace in array | `items[i] = x` | `map` |
| Change object field | `obj.f = x` | `{ ...obj, f: x }` |
Exercise
A component calls todos.push(newTodo) and then setTodos(todos). The list on screen does not change. Explain why, and write the corrected line.
Show answer
push changes the existing array, so setTodos receives the same reference the state already holds. Object.is reports no change, and React skips the re-render. The corrected line is setTodos([...todos, newTodo]);, which passes a new array.