Sub topic 6
Updating nested objects
This chapter assumes you know JavaScript objects and the spread operator, and that you can write a React function component that uses useState and handles events. Earlier chapters showed that spread copies an object one level deep. Here you apply that to objects that contain other objects.
Why one spread is not enough
Spread copies the properties of the top-level object. If a property holds another object, the copy receives a reference to the same inner object, not a new one.
Consider this state:
const [person, setPerson] = useState({
name: 'Ada',
address: { city: 'London', country: 'UK' },
});The update below looks reasonable, but it mutates the inner object:
function handleCityChange(e) {
const next = { ...person };
next.address.city = e.target.value; // mutates the old state's address
setPerson(next);
}next is a new outer object, but next.address and person.address are the same object. The assignment changes the previous snapshot too. Any component that receives person.address as a prop sees the same reference and may skip re-rendering.
Copy every object on the path
To change a nested value, copy each object between the top of the state and the value you want to change. Objects off that path can be shared safely.
In code, this is one spread per level:
import { useState } from 'react';
export default function Profile() {
const [person, setPerson] = useState({
name: 'Ada',
address: { city: 'London', country: 'UK' },
});
function handleCityChange(e) {
setPerson({
...person,
address: {
...person.address,
city: e.target.value,
},
});
}
return (
<label>
City:
<input value={person.address.city} onChange={handleCityChange} />
<p>
{person.name} lives in {person.address.city}, {person.address.country}.
</p>
</label>
);
}Read the update from the inside out. ...person.address copies country and city, then city: e.target.value overrides city. That object becomes the new address, which replaces the old one in the copy of person. The property that comes later in the literal wins, so the override must come after the spread.
Common errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| Spreading only the top level, then assigning to the nested object | The old snapshot is mutated through the shared reference | Spread each level on the path |
| Putting the override before the spread | The spread overwrites your new value with the old one | Write `...obj` first, then the changed property |
| Forgetting an inner spread: `address: { city: value }` | `country` is dropped from the new object | Add `...person.address` |
| Reading `e.target.value` inside a deferred callback | The event value may no longer be what you expect | Copy it to a variable first if you use it later |
When it gets repetitive
Three or four levels of spread become hard to read and easy to get wrong. Later chapters cover two ways to reduce this: keeping state flat, and using Immer to write the update as a mutation of a draft.
Exercise
State is { title: 'Trip', owner: { name: 'Sam', contact: { email: '[email protected]', phone: '123' } } }. Write the argument to setTrip that changes only the email to '[email protected]' without mutating the old state.
Show answer
{ ...trip, owner: { ...trip.owner, contact: { ...trip.owner.contact, email: '[email protected]' } } }. The objects on the path (trip, owner, contact) are each copied, and title, name, and phone are carried over by the spreads.