Sub topic 8
Why State Must Not Be Mutated
What this chapter assumes
You should know how useState returns a value and a setter, and how a call to the setter schedules a re-render. You should also be comfortable with object spread ({ ...obj }) and with the idea that each render sees a fixed snapshot of state. This chapter explains the rule behind the object and array chapters that follow: treat state as read-only and replace it instead of changing it.
Mutation versus replacement
JavaScript objects and arrays are reference types. A variable holds a reference to the data, not the data itself. Two operations look similar but behave differently:
- Mutation changes the data a reference points to:
person.score += 1oritems.push(x). The reference stays the same. - Replacement creates new data and gives React a new reference:
setPerson({ ...person, score: 1 }).
Primitive values (numbers, strings, booleans) are already immutable. You cannot change the number 5. You can only replace it with 6. This is why setCount(count + 1) always works. The rule matters for objects, arrays, Map, and Set.
What React compares
When you call a setter, React compares the new value with the current one using Object.is. If the two are identical, React skips the re-render and does not run your component again.
For objects, "identical" means the same reference. The contents are not compared. This produces the classic bug:
import { useState } from 'react';
function Broken() {
const [person, setPerson] = useState({ name: 'Ada', score: 0 });
function handleClick() {
person.score += 1; // mutates the existing object
setPerson(person); // same reference, so React bails out
}
return (
<button onClick={handleClick}>
{person.name}: {person.score}
</button>
);
}The object in memory does change on every click. The screen never updates, because React sees the same reference and decides nothing happened. The fix is to pass a new object:
setPerson({ ...person, score: person.score + 1 });Why mutation is harmful beyond the missed render
The missing re-render is the most visible symptom, but not the only one.
- It breaks snapshots. Each render closes over its own state. If a handler or timer from an earlier render holds a reference to the old object and you mutate that object, the "past" snapshot changes too. Code that was meant to see the old values now sees the new ones.
- It defeats reference-based optimizations.
React.memo,useMemo,useCallback, and dependency arrays inuseEffectall compare references. A mutated object keeps its reference, so these tools conclude nothing changed. - It removes history. If every update produces a new value, the old value still exists. That makes undo, comparing before and after, and debugging possible. Mutation overwrites the past.
- It makes updates unpredictable. React may render a component more than once, for example in Strict Mode during development. Render logic must give the same result each time, and mutating shared data during render does not.
A mutation that seems to work
Some mutations appear to work because something else triggers a re-render:
import { useState } from 'react';
function Sneaky() {
const [person, setPerson] = useState({ score: 0 });
const [clicks, setClicks] = useState(0);
function handleClick() {
person.score += 1; // mutation
setClicks(clicks + 1); // legitimate update, causes a render
}
return (
<button onClick={handleClick}>
{person.score} / {clicks}
</button>
);
}The display looks correct, because the second setClicks call re-renders the component and the render reads the mutated object. The code is still wrong. Remove the clicks state later, or pass person to a memoized child, and it stops updating. Code that works only because of an unrelated update is a bug waiting for a refactor.
Shallow copies and nested data
Spread creates a shallow copy. It copies the top-level properties, but nested objects are still shared with the original. Changing a nested value through a shallow copy mutates the old state:
import { memo, useState } from 'react';
const Address = memo(function Address({ address }) {
return <p>City: {address.city}</p>;
});
function Profile() {
const [user, setUser] = useState({
name: 'Ada',
address: { city: 'London' },
});
function moveWrong() {
const next = { ...user };
next.address.city = 'Paris'; // address object is shared with old state
setUser(next);
}
function moveRight() {
setUser({
...user,
address: { ...user.address, city: 'Paris' },
});
}
return (
<>
<p>{user.name}</p>
<Address address={user.address} />
<button onClick={moveWrong}>Move (wrong)</button>
<button onClick={moveRight}>Move (right)</button>
</>
);
}With moveWrong, Profile re-renders because next is a new top-level object. Address receives the same address reference as before, so memo skips it and it keeps showing London. With moveRight, every object on the path from the root to the changed value is a new object, so Address re-renders.
The working rule is to copy every level between the root of the state and the value you change. Levels you do not touch can stay shared.
Common mutating operations to avoid
| Task | Mutates (avoid) | Replaces (use) |
|---|---|---|
| Add to an array | `push`, `unshift`, `splice` | `[...items, x]`, `[x, ...items]` |
| Remove from an array | `pop`, `shift`, `splice` | `filter`, `slice` |
| Replace an item | `items[i] = x` | `map` |
| Sort or reverse | `sort`, `reverse` | `[...items].sort()`, `toSorted()` |
| Set an object field | `obj.key = x` | `{ ...obj, key: x }` |
| Delete a field | `delete obj.key` | Destructure with rest: `const { key, ...rest } = obj` |
sort and reverse are easy to miss because they return the array, which makes them look like pure functions. They reorder the original in place. Copy first, then sort.
Practical guidance
- Do not hand-write deep copies for complicated nested state. Flatten the state shape where you can, which a later chapter covers, or use a library such as Immer.
structuredClonemakes a deep copy, but it copies everything. That breaks reference equality for parts that did not change and can cause extra re-renders in memoized children. Prefer copying only the path you modify.- Treat props as read-only for the same reasons. A child that mutates an object it received corrupts the parent's state.
- Freezing is a useful debugging tool. Calling
Object.freezeon initial state makes mutations throw errors in strict mode instead of failing silently.
Exercise
A component keeps const [items, setItems] = useState(['b', 'a']). A button handler runs items.sort(); setItems(items);. Explain why the list may not update on screen, and write a corrected handler.
Show answer
sort reorders the array in place and returns the same array. setItems(items) then passes the same reference that React already holds, so Object.is reports no change and React skips the re-render. The corrected handler copies first: setItems([...items].sort()); (or setItems(items.toSorted()) in environments that support it). The copy is a new reference, so React re-renders.