Advanced · 12 min
Immutable updates
Copy every changed level of nested state without changing the original.
Copy the changed path
An object spread is shallow. To update a nested object independently, create a new object at every level you change.
const original = { user: { name: "Ada", city: "Rome" } };
const updated = { ...original, user: { ...original.user, city: "Oslo" } };
console.log(original.user.city);
console.log(updated.user.city);Output
Rome Oslo
Update one array item
map() can replace the matching object and retain the other items. Copy the changed object instead of mutating it.
const tasks = [{ id: 1, done: false }, { id: 2, done: false }];
const updated = tasks.map(task => task.id === 2 ? { ...task, done: true } : task);
console.log(tasks[1].done);
console.log(updated[1].done);Output
false true
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Copy the nested update
Change the copied city to "Oslo" while preserving "Rome" in original. Display both cities.
Copy original.user when building updated.