Sub topic 7
Updating Nested Data Immutably
This chapter assumes you already know how spread syntax makes a shallow copy of an object or array, and how map and filter return new arrays without touching the original. Both were covered in earlier chapters. Here we combine them to change a value buried several levels deep inside a state object, without mutating anything.
The Core Rule: Copy Every Level on the Path
Spread copies only one level. When you change a deeply nested value, every object between the root and that value must be copied too. If you skip one, the new state still points at the old object at that level, and any change you make there leaks into the old state.
Think of the state as a tree. To change one leaf, you build new nodes from the root down to that leaf. Every node not on that path can be reused as it is.
const state = {
user: { name: 'Ada', address: { city: 'London' } },
settings: { theme: 'dark' }
};
const next = {
...state,
user: {
...state.user,
address: { ...state.user.address, city: 'Paris' }
}
};
console.log(state.user.address.city); // 'London'
console.log(next.settings === state.settings); // true, the unchanged branch is shared
console.log(next.user === state.user); // false, the changed path was copiedThe update has three spreads because three objects sit on the path to city: the root, user, and address. settings is not on the path, so next.settings is the same object as state.settings.
A later chapter covers why this reuse matters for memory and change detection. For now, follow the rule: copy the path, reuse everything else.
The Most Common Mistake: Copying Only the Top
The most common bug is to copy the outer object and then mutate something inside it.
const state = {
user: { name: 'Ada', address: { city: 'London' } }
};
const next = { ...state };
next.user.address.city = 'Paris'; // mutates the shared address object
console.log(state.user.address.city); // 'Paris', the old state changed too
console.log(next.user === state.user); // true, user was never copiednext is a new object, but next.user is still the old user. Writing through it changes the original. The bug hides easily because next !== state is true, so code that compares references at the top level thinks a proper copy was made.
Spread Order Matters
In an object literal, later properties override earlier ones. The spread must come first, and the changed property after it.
const user = { name: 'Ada', role: 'admin' };
const correct = { ...user, role: 'editor' };
const wrong = { role: 'editor', ...user };
console.log(correct.role); // 'editor'
console.log(wrong.role); // 'admin', the spread overwrote the new valueGetting the order backwards fails silently. The update looks right in code review and does nothing at runtime.
Objects Inside Arrays
Many states hold arrays of objects. To change one item, use map to build a new array. Return a copied object for the item that changes and the original for every other item.
const state = {
filter: 'all',
todos: [
{ id: 1, text: 'Write', done: false },
{ id: 2, text: 'Review', done: false }
]
};
function toggleTodo(state, id) {
return {
...state,
todos: state.todos.map(todo =>
todo.id === id ? { ...todo, done: !todo.done } : todo
)
};
}
const next = toggleTodo(state, 2);
console.log(state.todos[1].done); // false
console.log(next.todos[1].done); // true
console.log(next.todos[0] === state.todos[0]); // true, untouched item reusedThe path here is root, then the todos array, then the one matching item. All three are new. The first todo is reused.
Adding and removing items inside a nested array works the same way. Copy the parent and replace the array property:
const state = { todos: [{ id: 1, text: 'Write', done: false }] };
const withNew = {
...state,
todos: [...state.todos, { id: 2, text: 'Ship', done: false }]
};
const withoutFirst = {
...state,
todos: state.todos.filter(todo => todo.id !== 1)
};
console.log(state.todos.length); // 1
console.log(withNew.todos.length); // 2
console.log(withoutFirst.todos.length); // 0Arrays Inside Objects Inside Arrays
Deeper paths repeat the same two moves: spread for objects, and map (or another non-mutating method) for arrays. Here we add a tag to one todo's tags array:
const state = {
todos: [
{ id: 1, text: 'Write', tags: ['docs'] },
{ id: 2, text: 'Review', tags: [] }
]
};
function addTag(state, id, tag) {
return {
...state,
todos: state.todos.map(todo =>
todo.id === id ? { ...todo, tags: [...todo.tags, tag] } : todo
)
};
}
const next = addTag(state, 1, 'urgent');
console.log(state.todos[0].tags); // ['docs']
console.log(next.todos[0].tags); // ['docs', 'urgent']Calling todo.tags.push(tag) inside the map callback would be a bug even though map returns a new array. map copies the array, not the objects in it.
Keyed Collections and Computed Keys
Many apps store items in an object keyed by id instead of an array. This is often called normalized state. Updating one entry then needs a computed property name:
const state = {
byId: {
a1: { id: 'a1', title: 'Intro', views: 10 },
b2: { id: 'b2', title: 'Setup', views: 4 }
}
};
function incrementViews(state, id) {
const item = state.byId[id];
return {
...state,
byId: {
...state.byId,
[id]: { ...item, views: item.views + 1 }
}
};
}
const next = incrementViews(state, 'b2');
console.log(state.byId.b2.views); // 4
console.log(next.byId.b2.views); // 5
console.log(next.byId.a1 === state.byId.a1); // trueTo remove a key without delete, which mutates, use rest destructuring:
const byId = { a1: { title: 'Intro' }, b2: { title: 'Setup' } };
const { b2: _removed, ...rest } = byId;
console.log(Object.keys(byId)); // ['a1', 'b2']
console.log(Object.keys(rest)); // ['a1']When the key is in a variable, write const { [id]: _removed, ...rest } = byId;.
A Reusable Path Helper
Hand-written nested spreads get long and are easy to get wrong past three or four levels. A small helper that takes a path can do the copying for you:
function setIn(target, path, value) {
if (path.length === 0) return value;
const [key, ...rest] = path;
const child = target == null ? undefined : target[key];
const updated = setIn(child, rest, value);
// Nothing changed below: keep the original reference.
if (Object.is(updated, child) && target != null) return target;
if (Array.isArray(target)) {
const copy = [...target];
copy[key] = updated;
return copy;
}
return { ...target, [key]: updated };
}
const state = {
user: { name: 'Ada', address: { city: 'London' } },
todos: [{ id: 1, done: false }]
};
const a = setIn(state, ['user', 'address', 'city'], 'Paris');
const b = setIn(state, ['todos', 0, 'done'], true);
const c = setIn(state, ['user', 'name'], 'Ada');
console.log(a.user.address.city); // 'Paris'
console.log(b.todos[0].done); // true
console.log(state.todos[0].done); // false
console.log(c === state); // true, setting the same value is a no-opThe helper keeps the existing reference when the new value equals the old one. This matters for change detection, covered later: an update that changes nothing should not produce a new object. The helper also creates missing objects along the path, because spreading undefined into an object literal gives {}.
Helpers like this have limits. Paths given as strings or arrays are not type-checked, so a typo creates a new branch instead of failing. Matching an item by id, rather than by index, needs extra code. These limits are part of why libraries such as Immer exist, which a later chapter covers.
Common Errors and Their Symptoms
| Error | Symptom | Fix |
|---|---|---|
| Spreading only the root, then assigning deep | Old state changes; UI or history shows the new value in the past | Spread every object on the path |
| Spread placed after the new property | Update has no effect | Put `...obj` first, overrides after |
| `push`, `splice`, or `sort` on a nested array | Original array changes | Use spread, `filter`, `map`, or the copying methods |
| `delete` on a nested key | Original object loses the key | Use rest destructuring |
| Deep-cloning the whole state for each update | Correct but slow; every reference changes, so all change checks fire | Copy only the path |
| Returning a new object when nothing changed | Unneeded re-renders or recomputation | Return the original when the value is the same |
Edge Cases Worth Knowing
- Spread drops prototypes and getters.
{ ...instance }copies own enumerable properties into a plain object. Class instances lose their methods, and getters are replaced by their current values. Keep nested state as plain objects and arrays, or copy class instances with their own methods. - Map and Set need their own copy. Spreading a
Mapinto an object literal gives{}. Usenew Map(oldMap).set(key, value)to get an updated copy. - Sparse paths. Writing to a path that does not exist yet means creating every missing level. The
setInhelper does this. Hand-written spreads need a fallback such as...(state.user ?? {}). - Array index writes.
copy[key] = updatedon a fresh copy is fine, because the copy is yours. You can also writetarget.with(key, updated), covered in the chapter on ES2023 copying methods. Note thatwiththrows aRangeErrorfor an index past the end, while assigning to a copy extends the array.
Exercise
Given const state = { teams: [{ id: 't1', members: [{ id: 'm1', active: true }] }] };, write an expression that returns a new state where member m1 in team t1 has active: false, without mutating state. Which objects and arrays are new in the result?
Show answer
({ ...state, teams: state.teams.map(team => team.id === 't1' ? { ...team, members: team.members.map(m => m.id === 'm1' ? { ...m, active: false } : m) } : team) }). New: the root object, the teams array, the t1 team object, its members array, and the m1 member object. Any other teams or members would be reused unchanged.
Exercise
A teammate writes const next = { ...state, user: state.user }; next.user.prefs.theme = 'light'; and says the update is immutable because next !== state. What is wrong, and how would you fix it?
Show answer
Only the root was copied. next.user and next.user.prefs are the same objects as in state, so the assignment changes state.user.prefs.theme too. Fix it by copying each level on the path: const next = { ...state, user: { ...state.user, prefs: { ...state.user.prefs, theme: 'light' } } };.
Exercise
Why does the setIn helper return target when Object.is(updated, child) is true, and what would go wrong without that check?
Show answer
If the value at the end of the path did not change, no level above it changed either, so the original references can be kept. Without the check, setting a value to what it already is would still create new objects along the whole path. Code that detects changes by comparing references would then report a change that never happened, which causes extra re-renders or recomputation.