Sub topic 4
Updating objects and arrays immutably
This chapter assumes you know the spread operator, map and filter, and the reducer shape (state, action) => nextState from the previous chapters. It covers how to write the "next state" part without changing the old state.
Why reducers must not mutate
To mutate a value is to change it in place. React decides whether to re-render by comparing the state your reducer returns with the previous state, using Object.is. That check only tests whether the two values are the same reference. If you change state.count and return state, the reference is identical, so React treats it as "nothing changed" and skips the update.
// Wrong: mutates the existing object and returns it
function badReducer(state, action) {
if (action.type === 'incremented') {
state.count++;
return state;
}
return state;
}Mutation also breaks under Strict Mode. In development, React calls your reducer twice to expose impure code. A mutating reducer would apply the change twice.
Copying objects and arrays
The rule is to build a new value that contains the change and leave the old one alone. Spread copies the top-level properties, and the properties you list afterward replace the copied ones.
| Task | Mutating (avoid) | Immutable |
|---|---|---|
| Set a property | `obj.name = x` | `{ ...obj, name: x }` |
| Add to an array | `arr.push(x)` | `[...arr, x]` |
| Replace an item | `arr[i] = x` | `arr.map(...)` |
| Remove an item | `arr.splice(i, 1)` | `arr.filter(...)` |
| Sort | `arr.sort()` | `[...arr].sort()` |
Nested state
Spread is shallow. It copies the top level only, so nested objects are still shared with the old state. To change a nested value, copy every level on the path to it. Everything off that path can be reused.
function profileReducer(state, action) {
switch (action.type) {
case 'renamed':
return { ...state, name: action.name };
case 'city_changed':
return {
...state,
address: { ...state.address, city: action.city },
};
case 'tag_added':
return { ...state, tags: [...state.tags, action.tag] };
case 'tag_renamed':
return {
...state,
tags: state.tags.map(t => (t === action.from ? action.to : t)),
};
case 'tag_removed':
return { ...state, tags: state.tags.filter(t => t !== action.tag) };
default:
throw Error('Unknown action: ' + action.type);
}
}
const before = {
name: 'Ada',
address: { city: 'Lyon' },
tags: ['admin', 'beta'],
};
const after = profileReducer(before, { type: 'city_changed', city: 'Oslo' });
console.log(after.address.city); // Oslo
console.log(before.address.city); // Lyon
console.log(after.tags === before.tags); // trueThe old state is untouched, and after.tags is the same array as before.tags because nothing in it changed. Sharing unchanged parts keeps copies cheap. It also lets React.memo skip children whose props kept the same reference.
Common errors
- Copying only the outer object.
{ ...state }followed bycopy.address.city = xstill mutates the sharedaddressobject. - Forgetting to return in a case. The reducer returns
undefined, and the state is lost on the next render. - Using
mapwithout a fallback branch. Return the original item for non-matching elements, as int.id === action.id ? { ...t, done: !t.done } : t. - Putting the spread last. In
{ name: x, ...state }, the oldnameoverwrites the new one. Spread first, then the changes. - Deep copying everything.
JSON.parse(JSON.stringify(state))is slow and drops values like dates andundefined. Copy only the path you change.
If nesting becomes painful, flatten the state shape. For example, keep a list of items by id instead of objects nested several levels deep.
Exercise
A reducer handles { type: 'moved', id, folder } for state shaped as { files: [{ id, name, folder }] }. Write the case so it returns new state without mutating, and say which parts of the old state are reused.
Show answer
case 'moved': return { ...state, files: state.files.map(f => f.id === action.id ? { ...f, folder: action.folder } : f) }; The files that did not match keep their old object references. Any other top-level fields of state are also reused, because the spread copies their references.