Sub topic 2
Updating Nested Objects
Assume you know JavaScript objects, arrays, map, filter, slice, and React’s useState hook. React state should be treated as read-only. Create a new value instead of changing the existing value.
Updating nested objects
The spread operator makes a shallow copy. When updating a nested property, copy every object on the path to that property:
const [person, setPerson] = useState({
name: 'Ada',
address: { city: 'London', country: 'UK' },
});
function handleCityChange(event) {
setPerson({
...person,
address: {
...person.address,
city: event.target.value,
},
});
}The outer object and address object are new. The unchanged country value is reused. This matters because changing person.address.city directly would mutate the state snapshot.
Which array methods mutate and which do not
Some array methods change the array they receive. Do not call those methods directly on state.
| Mutates the array | Returns a new array |
|---|---|
| `push`, `pop`, `splice`, `sort`, `reverse` | `map`, `filter`, `slice`, `concat` |
For a mutating method, first copy the array:
const nextItems = [...items];
nextItems.sort((a, b) => a.name.localeCompare(b.name));
setItems(nextItems);Adding to an array
Use spread to create an array containing the old items and the new item:
setTodos((previousTodos) => [
...previousTodos,
{ id: crypto.randomUUID(), title: 'Read', done: false },
]);The updater function receives the latest state. Use it when the new value depends on the previous value, especially when several updates may be queued.
Removing from an array with `filter`
filter returns every item that passes its test. To remove one item, keep items whose identifiers do not match:
function removeTodo(id) {
setTodos((previousTodos) =>
previousTodos.filter((todo) => todo.id !== id)
);
}Changing items with `map`
Use map to replace one item while returning the other items unchanged:
function toggleTodo(id) {
setTodos((previousTodos) =>
previousTodos.map((todo) =>
todo.id === id ? { ...todo, done: !todo.done } : todo
)
);
}The changed todo receives a new object. The other todo objects keep their references.
Exercise
How would you remove the todo with id 3 without mutating the array?
Show answer
setTodos((previousTodos) => previousTodos.filter((todo) => todo.id !== 3));