Sub topic 4
Updating Objects and Arrays Immutably
This chapter assumes you know JavaScript objects, arrays, and the spread operator, and that you have written a basic reducer and called useReducer (covered in the previous chapters). It focuses on one rule: a reducer never changes the state it receives. It builds and returns a new value instead.
Why reducers must not mutate
React decides whether to re-render by comparing the new state to the old state with Object.is. For objects and arrays, that compares references, not contents. If a reducer changes the existing object and returns it, the reference is the same. React concludes nothing changed and skips the update.
const before = { count: 0 };
// Mutation: same reference, so React sees "no change"
const mutated = before;
mutated.count = 1;
console.log(Object.is(before, mutated)); // true
// Copy: new reference, so React sees a change
const copied = { ...before, count: 2 };
console.log(Object.is(before, copied)); // false
console.log(before.count); // 1, the original is untouchedHere is a reducer that makes this mistake:
function buggyReducer(state, action) {
switch (action.type) {
case 'incremented':
state.count++; // mutates the existing object
return state; // same reference, so React bails out
default:
throw Error('Unknown action: ' + action.type);
}
}The screen does not update, even though the state object now holds a larger number. The bug can also appear only some of the time. If another state change triggers a re-render, the mutated value suddenly shows up. This makes mutation bugs hard to trace.
Mutation has two more costs:
- In development, Strict Mode calls your reducer twice with the same arguments to expose impure code. A reducer that does
state.count++increments twice per dispatch. - Past states stop being reliable snapshots. Memoized components,
useEffectdependency arrays, and debugging tools all rely on old values staying as they were.
Updating objects
To change one property, copy the object with spread and then overwrite the property. Properties listed after the spread win.
function profileReducer(profile, action) {
switch (action.type) {
case 'name_changed':
return { ...profile, name: action.name };
case 'email_changed':
return { ...profile, email: action.email };
default:
throw Error('Unknown action: ' + action.type);
}
}Order matters. { name: action.name, ...profile } would let the old profile.name overwrite the new one.
Nested objects need a copy at every level
Spread is shallow. It copies the top-level properties, and nested objects are shared with the original by reference. To change a deeply nested value, copy every object on the path from the root down to it.
function reducer(state, action) {
switch (action.type) {
case 'city_changed':
return {
...state,
user: {
...state.user,
address: {
...state.user.address,
city: action.city,
},
},
};
default:
throw Error('Unknown action: ' + action.type);
}
}This pattern is called path copying. Everything off the path (for example state.items) keeps its old reference. That is intended, because unchanged parts stay identical and memoized children that receive them skip re-rendering.
If you write state.user.address.city = action.city and then return { ...state }, you have copied only the root. The nested address object is still mutated, and any component that holds the old address reference sees the change without a re-render.
Updating arrays
Many array methods change the array in place. Prefer methods that return a new one.
| Task | Avoid (mutates) | Prefer (returns a new array) |
|---|---|---|
| Add to the end | `push`, `unshift` | `[...arr, item]`, `[item, ...arr]` |
| Remove | `splice`, `pop`, `shift` | `filter` |
| Replace or change one item | `arr[i] = x` | `map` |
| Insert at an index | `splice(i, 0, x)` | `[...arr.slice(0, i), x, ...arr.slice(i)]` |
| Sort or reverse | `sort`, `reverse` | `[...arr].sort()`, `toSorted()`, `toReversed()` |
sort and reverse catch people out because they look harmless, but they reorder the array they are called on. Copy first, or use toSorted and toReversed. These were added in ES2023, so check that your target browsers and Node version support them.
slice and splice have similar names but opposite behavior. slice copies a range and leaves the original alone. splice removes and inserts items in place.
A reducer that combines both
The next component keeps a nested object and an array in one state. Each case copies only what it changes.
import { useReducer } from 'react';
const initialState = {
user: { name: 'Ada', address: { city: 'London', zip: 'N1' } },
items: [
{ id: 1, name: 'Tea', qty: 1 },
{ id: 2, name: 'Milk', qty: 2 },
],
};
function reducer(state, action) {
switch (action.type) {
case 'city_changed':
return {
...state,
user: {
...state.user,
address: { ...state.user.address, city: action.city },
},
};
case 'qty_increased':
return {
...state,
items: state.items.map(item =>
item.id === action.id ? { ...item, qty: item.qty + 1 } : item
),
};
case 'item_inserted':
return {
...state,
items: [
...state.items.slice(0, action.index),
action.item,
...state.items.slice(action.index),
],
};
case 'item_removed':
return {
...state,
items: state.items.filter(item => item.id !== action.id),
};
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function Basket() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
<p>
{state.user.name} lives in {state.user.address.city}
</p>
<button onClick={() => dispatch({ type: 'city_changed', city: 'Paris' })}>
Move to Paris
</button>
<button
onClick={() =>
dispatch({
type: 'item_inserted',
index: 1,
item: { id: 3, name: 'Bread', qty: 1 },
})
}
>
Insert bread at position 1
</button>
<ul>
{state.items.map(item => (
<li key={item.id}>
{item.name} x {item.qty}
<button onClick={() => dispatch({ type: 'qty_increased', id: item.id })}>
+1
</button>
<button onClick={() => dispatch({ type: 'item_removed', id: item.id })}>
Remove
</button>
</li>
))}
</ul>
</>
);
}Look at qty_increased. The map callback returns the original item for every row except the one that matched. Only that row gets a new object, so only components that receive that row as a prop need to re-render if they are memoized.
If you click "Insert bread" twice, the second click adds another item with id: 3. The key values then collide, which React warns about. Real code generates ids in the event handler, as the todo example in the previous chapter did, not inside the reducer.
Catching mutations early
You can enforce immutability in a test by freezing the state before calling the reducer. In strict mode, which ES modules always use, assigning to a frozen object throws. Without strict mode, the assignment fails silently, so add 'use strict' to CommonJS scripts like this one.
'use strict';
function deepFreeze(value) {
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
Object.freeze(value);
Object.values(value).forEach(deepFreeze);
}
return value;
}
function reducer(state, action) {
switch (action.type) {
case 'qty_increased':
return {
...state,
items: state.items.map(item =>
item.id === action.id ? { ...item, qty: item.qty + 1 } : item
),
};
default:
throw Error('Unknown action: ' + action.type);
}
}
const before = deepFreeze({
items: [
{ id: 1, qty: 1 },
{ id: 2, qty: 5 },
],
});
const after = reducer(before, { type: 'qty_increased', id: 1 });
console.log(after.items[0].qty); // 2
console.log(before.items[0].qty); // 1
console.log(after.items[1] === before.items[1]); // true, unchanged row is shared
console.log(after === before); // falseIf the reducer tried item.qty++, the frozen object would throw a TypeError and the test would fail at the exact line that mutates.
Gotchas and edge cases
- Spread copies only the top level.
{ ...state }and[...items]are shallow. Items inside a copied array are still the same objects, socopy[0].done = truealso changes the original. - Returning the same state is allowed. If an action changes nothing,
return stateis correct, and React skips the render. This is intentional bail-out behavior, not a bug. The bug is returning the same reference after changing it. - Classes,
Map,Set, andDateneed their own copy. Spread on aMapgives you an empty object. Usenew Map(oldMap)and then set a value on the new map, or store plain objects and arrays when you can. - Removing the wrong thing.
filterbyid, not by index, when ids exist. Indices shift after other edits and actions can arrive in a different order than you expected. structuredCloneworks but is a blunt tool. It deep-copies everything, so every reference changes and memoization stops helping. Use it when a state shape is small and updates are rare.- Deeply nested state is a design smell. Each extra level adds another spread to every case. Flatten the state, for example by keeping items in an array and referring to them by id, before reaching for a library.
- Immer is an option. The
use-immerpackage offersuseImmerReducer, where you write mutating-looking code inside the reducer and Immer produces the immutable result. It is a separate dependency and is not part of React.
Exercises
Exercise
This reducer case is meant to mark one todo as done, but the UI sometimes does not update. Find the problem and rewrite it. case 'toggled': { const todo = state.find(t => t.id === action.id); todo.done = !todo.done; return state; }
Show answer
It mutates the todo object and returns the same array reference, so React bails out of the render. Rewrite it so that both the array and the changed item are new: case 'toggled': return state.map(t => (t.id === action.id ? { ...t, done: !t.done } : t));
Exercise
State is { settings: { theme: 'light', notifications: { email: true, sms: false } } }. Write a reducer case 'sms_toggled' that flips settings.notifications.sms immutably, and say which objects keep their old reference.
Show answer
case 'sms_toggled': return { ...state, settings: { ...state.settings, notifications: { ...state.settings.notifications, sms: !state.settings.notifications.sms, }, }, }; The root state, settings, and notifications objects are all new because they lie on the path to the change. Nothing else in this state has a reference to preserve, since theme and email are primitive values copied by the spread.
Exercise
A reducer sorts a list with return { ...state, items: state.items.sort(byName) }. Why is this wrong even though items appears inside a new object, and what are two correct fixes?
Show answer
sort reorders the existing state.items array in place and returns that same array, so the previous state is mutated and the items reference is unchanged. Two fixes: [...state.items].sort(byName) or state.items.toSorted(byName) (ES2023).