Sub topic 11
Updating immutable state in React and Redux
This chapter assumes you know how toSorted, toSpliced, and with work, and what a shallow copy shares with its original. It also assumes basic familiarity with React's useState or a Redux reducer. You do not need either library to run the examples, because they are plain functions.
Why reference changes matter
React and Redux decide whether state changed by comparing references with Object.is. They do not compare contents. If you mutate an array in place and pass it back, the reference stays the same. React then skips the re-render, and Redux selectors return stale results.
const state = [3, 1, 2];
const mutated = state;
mutated.sort();
console.log(Object.is(state, mutated)); // true, so the change goes unnoticed
const fresh = [3, 1, 2];
const copied = fresh.toSorted();
console.log(Object.is(fresh, copied)); // false, so a change is detectedThe copying methods always return a new array. That makes them a direct fit for the "never mutate state" rule.
A reducer built on the copying methods
Each common list operation maps to one copying method:
| Operation | Mutating version | Copying version |
|---|---|---|
| Update one item | `arr[i] = x` | `arr.with(i, x)` |
| Insert at a position | `arr.splice(i, 0, x)` | `arr.toSpliced(i, 0, x)` |
| Remove at a position | `arr.splice(i, 1)` | `arr.toSpliced(i, 1)` |
| Reorder | `arr.sort(cmp)` | `arr.toSorted(cmp)` |
Here is a todo reducer that uses them:
function todosReducer(state, action) {
switch (action.type) {
case "toggle": {
const i = state.findIndex((t) => t.id === action.id);
if (i === -1) return state;
return state.with(i, { ...state[i], done: !state[i].done });
}
case "insert":
return state.toSpliced(action.index, 0, action.todo);
case "remove": {
const i = state.findIndex((t) => t.id === action.id);
return i === -1 ? state : state.toSpliced(i, 1);
}
case "sortByText":
return state.toSorted((a, b) => a.text.localeCompare(b.text));
default:
return state;
}
}
let todos = [
{ id: 1, text: "Write", done: false },
{ id: 2, text: "Review", done: false }
];
const before = todos;
todos = todosReducer(todos, { type: "toggle", id: 2 });
todos = todosReducer(todos, { type: "insert", index: 0, todo: { id: 3, text: "Plan", done: false } });
todos = todosReducer(todos, { type: "sortByText" });
console.log(todos.map((t) => `${t.text}:${t.done}`)); // ["Plan:false", "Review:true", "Write:false"]
console.log(before[1].done); // false, the original state is untouched
console.log(todosReducer(todos, { type: "remove", id: 99 }) === todos); // trueWhen nothing changes, the reducer returns the same state. That lets React and Redux skip work. Returning a fresh copy on every action would trigger needless re-renders.
In a React component the same calls go inside a functional setter:
// Inside a component: const [items, setItems] = useState([...]);
// setItems((prev) => prev.with(index, { ...prev[index], done: true }));
// setItems((prev) => prev.toSpliced(index, 1));Common errors
- Changing the element object in place.
state.with(i, state[i])afterstate[i].done = truegives you a new array, but the old state's object has already been mutated. Always spread the element, as in{ ...state[i], done: true }. - Calling
with(-1, …)when you meant "not found".findIndexreturns-1, andwith(-1, x)silently replaces the last element. Check for-1first. - Out-of-range indices.
withthrows aRangeErrorfor an index outside the array, which can crash a reducer.toSplicedclamps the index instead, so it never throws. - Redux Toolkit reducers. Immer drafts in
createSliceare designed for mutation. Inside those reducers you can callsortdirectly, or return atoSortedresult. Do not do both in the same reducer.
Exercise
A reducer handles "rename" with const i = state.findIndex(t => t.id === action.id); return state.with(i, { ...state[i], text: action.text });. What goes wrong when the id does not exist, and how do you fix it?
Show answer
findIndex returns -1, so with(-1, ...) replaces the last todo with a copy of undefined spread plus the new text, producing a corrupted item. Guard with if (i === -1) return state; before calling with.
Exercise
Why does state.sort(cmp); return state; fail to re-render in React, while return state.toSorted(cmp); works?
Show answer
sort reorders the same array in place, so the returned reference is identical and Object.is reports no change. toSorted returns a new array, so the reference differs and React re-renders.