Sub topic 11
Updating immutable state in React and Redux
This chapter assumes you already know toSorted, toSpliced, and with from the earlier chapters, and that you understand shallow copies. It also assumes basic familiarity with React's useState hook and Redux reducers. You do not need a React project to run most examples. The reducer code runs in plain Node.js.
Why UI frameworks care about references
React and Redux both decide whether something changed by comparing references, not by inspecting contents. When you call a state setter in React, React compares the old and new values with Object.is. If the two values are the same object, React may skip the re-render. Redux's useSelector and React.memo use the same kind of cheap reference check.
This is why mutation causes bugs in state-driven code. If you sort an array in place and pass the same array back, its contents changed but its reference did not. To the framework, nothing happened.
The following script simulates that check without React:
function wouldRender(prev, next) {
return Object.is(prev, next) ? "skipped" : "re-rendered";
}
const scores = [40, 100, 1, 5];
// Mutating: same reference, so the update is skipped
const mutated = scores;
mutated.sort((a, b) => a - b);
console.log(wouldRender(scores, mutated)); // "skipped"
// Copying: new reference, so the update goes through
const fresh = [40, 100, 1, 5];
const sorted = fresh.toSorted((a, b) => a - b);
console.log(wouldRender(fresh, sorted)); // "re-rendered"
console.log(fresh); // [40, 100, 1, 5]The copying methods always return a new array. That gives the framework the reference change it needs, and the old state stays intact for undo history, time-travel debugging, and comparison.
Mapping state operations to copying methods
Most list updates in UI code fall into a few patterns. Each has a mutating version that breaks change detection and a copying version that works.
| Operation | Mutating (avoid in state) | Copying replacement |
|---|---|---|
| Sort for storage | `list.sort(cmp)` | `list.toSorted(cmp)` |
| Reverse | `list.reverse()` | `list.toReversed()` |
| Insert at index | `list.splice(i, 0, item)` | `list.toSpliced(i, 0, item)` |
| Remove at index | `list.splice(i, 1)` | `list.toSpliced(i, 1)` |
| Replace at index | `list[i] = item` | `list.with(i, item)` |
| Append | `list.push(item)` | `[...list, item]` |
| Remove by condition | loop with `splice` | `list.filter(fn)` |
Before ES2023, the copying column was written with spread and slice, as in [...list.slice(0, i), item, ...list.slice(i)]. The new methods state the intent in one call and are harder to get wrong.
Updating one item: `with` plus object spread
Toggling a todo is the classic case. The array needs a new reference, and the changed todo also needs a new reference, because components that render a single todo may be memoized on it. As the shallow-copy chapter showed, with alone copies only the array, so you pair it with object spread.
This pattern is called structural sharing. Only the path to the change is copied. Everything else is reused, so unchanged items keep their references and memoized children skip their renders.
The `findIndex` and `-1` trap
You usually find the index by id with findIndex. When no item matches, findIndex returns -1. Because with accepts negative indices, with(-1, value) does not throw. It replaces the last element instead, which corrupts your state with no error.
const todos = [
{ id: 1, text: "Write", done: false },
{ id: 2, text: "Review", done: false }
];
// Buggy: an unknown id overwrites the last todo
function toggleBuggy(list, id) {
const index = list.findIndex((t) => t.id === id);
return list.with(index, { ...list[index], done: true });
}
console.log(toggleBuggy(todos, 99)[1]); // { done: true }; the "Review" todo is gone
// Safe: guard the index and return the same reference when nothing changes
function toggle(list, id) {
const index = list.findIndex((t) => t.id === id);
if (index === -1) return list;
return list.with(index, { ...list[index], done: !list[index].done });
}
console.log(toggle(todos, 99) === todos); // true (no re-render)
console.log(toggle(todos, 2)[1].done); // true
console.log(todos[1].done); // falseWhen nothing changes, return the original array. A new but identical array still forces a re-render.
A Redux reducer built on copying methods
A Redux reducer must be a pure function: given the same state and action, it returns a result without changing its inputs. The copying methods fit this rule directly. The reducer below handles adding, removing, toggling, and moving todos, and it runs as written in Node.js.
function todosReducer(state = [], action) {
switch (action.type) {
case "todos/added": {
const at = action.index ?? state.length;
return state.toSpliced(at, 0, { id: action.id, text: action.text, done: false });
}
case "todos/removed": {
const index = state.findIndex((t) => t.id === action.id);
return index === -1 ? state : state.toSpliced(index, 1);
}
case "todos/toggled": {
const index = state.findIndex((t) => t.id === action.id);
if (index === -1) return state;
return state.with(index, { ...state[index], done: !state[index].done });
}
case "todos/moved": {
const { from, to } = action;
if (from < 0 || from >= state.length || to < 0 || to >= state.length) return state;
const item = state[from];
return state.toSpliced(from, 1).toSpliced(to, 0, item);
}
default:
return state;
}
}
let state = todosReducer(undefined, { type: "@@init" });
state = todosReducer(state, { type: "todos/added", id: 1, text: "Write" });
state = todosReducer(state, { type: "todos/added", id: 2, text: "Review" });
state = todosReducer(state, { type: "todos/added", id: 3, text: "Ship", index: 0 });
state = todosReducer(state, { type: "todos/toggled", id: 1 });
state = todosReducer(state, { type: "todos/moved", from: 0, to: 2 });
state = todosReducer(state, { type: "todos/removed", id: 2 });
console.log(state.map((t) => `${t.id}:${t.text}:${t.done}`));
// ["1:Write:true", "3:Ship:false"]
console.log(todosReducer(state, { type: "todos/toggled", id: 99 }) === state); // trueThe moved case chains two toSpliced calls. The first removes the item and the second inserts it at the target index. Each call returns a new array, so the chain never touches state. The range check matters here: without it, negative values would be counted from the end.
Redux Toolkit and Immer
Redux Toolkit's createSlice runs reducers through Immer. Immer hands you a draft that you may mutate, so state.push(todo) is correct there. If you use a copying method inside such a reducer, you must return its result. Calling state.toSorted(cmp) on a line by itself does nothing, because the new array is thrown away. Immer also rejects a reducer that both mutates the draft and returns a new value, so choose one style per case.
Using the methods in React components
In React, pass an updater function to the setter so the update always starts from the latest state:
import { useMemo, useState } from "react";
export default function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: "Write", done: false },
{ id: 2, text: "Review", done: true }
]);
const visible = useMemo(
() => todos.toSorted((a, b) => Number(a.done) - Number(b.done)),
[todos]
);
function toggle(id) {
setTodos((prev) => {
const index = prev.findIndex((t) => t.id === id);
if (index === -1) return prev;
return prev.with(index, { ...prev[index], done: !prev[index].done });
});
}
return (
<ul>
{visible.map((t) => (
<li key={t.id} onClick={() => toggle(t.id)}>
{t.done ? "✓ " : ""}
{t.text}
</li>
))}
</ul>
);
}The sorted list is derived data, not state. Before ES2023, writing todos.sort(...) during render was a common bug because it mutated state while React was rendering. toSorted inside useMemo produces a display order and leaves the stored order alone.
Selectors that return new arrays
The fact that copying methods always return a new reference can also work against you. A Redux selector such as useSelector((s) => s.todos.toSorted(cmp)) returns a fresh array on every call. useSelector sees a "change" after every dispatch, so the component re-renders even when the todos are untouched. In development builds, React Redux warns about selectors that return different results for the same input. Memoize derived arrays with createSelector from Reselect (re-exported by Redux Toolkit), or select the raw array and sort it in useMemo.
Nested updates
Because the copies are shallow, every level on the path to a change needs its own copy. Here is a board whose columns hold cards:
const board = [
{ id: "todo", cards: [{ id: "a", title: "Draft" }, { id: "b", title: "Edit" }] },
{ id: "done", cards: [{ id: "c", title: "Plan" }] }
];
function renameCard(board, colIndex, cardIndex, title) {
const col = board[colIndex];
const card = col.cards[cardIndex];
return board.with(colIndex, {
...col,
cards: col.cards.with(cardIndex, { ...card, title })
});
}
const next = renameCard(board, 0, 1, "Polish");
console.log(next[0].cards[1].title); // "Polish"
console.log(board[0].cards[1].title); // "Edit"
console.log(next[1] === board[1]); // true (untouched column is shared)If nesting grows deeper than two or three levels, consider normalizing state into a lookup keyed by id. You can also let Immer write the copies for you.
Cost and trade-offs
Each copying call allocates a new array and runs in O(n) time. For lists of hundreds or a few thousand items, this cost is small next to rendering. Chains like toSpliced(...).toSpliced(...) allocate an intermediate array per step. That is usually fine, but a hot path over very large arrays may justify mutating a local copy once and returning it. Mutating a copy you just created is safe, because no other code holds a reference to it.
Exercise
A reducer handles "todos/removed" with const i = state.findIndex(t => t.id === action.id); return state.toSpliced(i, 1);. What happens when the id does not exist, and how do you fix it?
Show answer
findIndex returns -1, and toSpliced(-1, 1) removes the last todo, so an unrelated item silently disappears. Guard the index: return i === -1 ? state : state.toSpliced(i, 1);. Returning the original state also avoids a needless re-render.
Exercise
A component calls useSelector(s => s.todos.toSorted((a, b) => a.text.localeCompare(b.text))) and re-renders after every dispatch, even unrelated ones. Why, and what are two fixes?
Show answer
toSorted returns a new array on every call, so useSelector's reference comparison always reports a change. Fix it by memoizing with createSelector so the sorted array is recomputed only when s.todos changes, or by selecting s.todos directly and sorting inside useMemo with [todos] as the dependency.
Exercise
Using with and object spread, write setDone(list, index) that marks the item at a non-negative index as done and returns the original array when the index is out of range or the item is already done.
Show answer
function setDone(list, index) { if (index < 0 || index >= list.length || list[index].done) return list; return list.with(index, { ...list[index], done: true }); } The explicit range check prevents both a RangeError and the negative-index wraparound, and the early return keeps the reference stable when nothing changes.