Sub topic 2
Why Mutating State Does Not Work
This chapter assumes you know JavaScript objects and the spread operator, basic function components, the useState hook, and React event handlers.
State is a snapshot
Each time React renders a component, it gives that render one fixed value for each state variable. That value is a snapshot. The setter function (setPerson below) does not edit the snapshot. It asks React to render again with a new value.
React decides whether to render again by comparing the value you pass to the setter with the current one, using Object.is. For objects and arrays, this compares references (the identity of the object), not the contents.
What goes wrong when you mutate
Here is a form that mutates the state object and passes the same object back:
import { useState } from 'react';
export default function Form() {
const [person, setPerson] = useState({
firstName: 'Ada',
lastName: 'Lovelace',
});
function handleFirstNameChange(e) {
person.firstName = e.target.value; // mutates the current state object
setPerson(person); // passes the same reference back
}
return (
<>
<input value={person.firstName} onChange={handleFirstNameChange} />
<p>
{person.firstName} {person.lastName}
</p>
</>
);
}Typing in the input does not reliably update the screen. The setter receives the same object that is already in state, so Object.is(person, person) is true. React concludes nothing changed and skips the render.
Why the failure is hard to notice
Mutation does change the data in memory. So the bug can look intermittent. If something else triggers a render, such as another state update, the component reads the mutated object and the new text suddenly appears.
Mutation causes other problems too:
- It rewrites the snapshot of the current render, so code that still holds the old value sees it change.
- Code that relies on reference comparison, such as
React.memoor dependency arrays inuseEffect, cannot detect the change.
The fix: pass a new object
Build a new object with the changed value and pass that to the setter:
function handleFirstNameChange(e) {
setPerson({ ...person, firstName: e.target.value });
}The spread (...person) copies the existing properties into a new object, and firstName then overrides one of them. The reference differs, so React renders again.
| Approach | Reference passed to setter | React renders? |
|---|---|---|
| `person.firstName = value; setPerson(person)` | Same | No |
| `setPerson({ ...person, firstName: value })` | New | Yes |
Treat state as read-only
The rule is to treat every object and array in state as read-only. To change something, make a copy that contains the change and pass the copy to the setter. The next chapters apply this rule to nested objects and to arrays.
Exercise
A component keeps const [user, setUser] = useState({ name: 'Sam', age: 30 }). A button handler runs user.age = user.age + 1; setUser(user);. The age on screen does not change. Explain why, and write the corrected line.
Show answer
The setter receives the same object reference that is already in state. React compares it with Object.is, finds no difference, and skips the render. The fix is to pass a new object: setUser({ ...user, age: user.age + 1 });