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 with useState and an onChange handler. It also assumes you have seen the basic pattern of updating a flat object: setPerson({ ...person, firstName: 'Grace' }). Here we extend that pattern to objects that contain other objects.
The problem with nesting
A flat state object has one level of properties. Spreading it into a new object is enough, because every value is a string, number, or boolean.
Nested state looks like this:
const [person, setPerson] = useState({
name: 'Ada',
address: { city: 'London', country: 'UK' },
});Here person is one object, and person.address is a second, separate object. To React, a change to city is a change to the inner object. React still has to receive a new top-level value from the setter. That means the update has to create new objects at more than one level.
Copy every object on the path
The rule is: copy each object on the path from the root to the value you change. Leave everything else alone.
import { useState } from 'react';
export default function PersonForm() {
const [person, setPerson] = useState({
name: 'Ada',
address: { city: 'London', country: 'UK' },
});
function handleNameChange(e) {
setPerson({ ...person, name: e.target.value });
}
function handleCityChange(e) {
setPerson({
...person,
address: { ...person.address, city: e.target.value },
});
}
return (
<>
<label>
Name:
<input value={person.name} onChange={handleNameChange} />
</label>
<label>
City:
<input value={person.address.city} onChange={handleCityChange} />
</label>
<p>
{person.name} lives in {person.address.city}, {person.address.country}.
</p>
</>
);
}Read handleCityChange from the inside out:
{ ...person.address, city: e.target.value }builds a new address object. It copiescityandcountry, then replacescity.{ ...person, address: <new address> }builds a new person object. It copiesnameandaddress, then replacesaddresswith the new one.setPersonreceives the new person object.
Order matters inside each object literal. In { ...person.address, city: value }, the later key wins, so city overrides the copied city. If you wrote { city: value, ...person.address }, the old city would overwrite your new one and the input would appear frozen.
What gets copied and what gets shared
Only the objects on the path are new. Everything off the path is reused by reference. Suppose person also had a hobbies array. After the city update, the new person object would point to the same hobbies array as the old one.
This sharing is safe because you never mutate shared pieces. It is also cheap, since you copy a few properties per level and not the whole tree. The old snapshot stays intact, which matters for event handlers that already captured it.
Updating deeper levels
Each extra level of nesting adds one more spread. Consider settings three levels deep:
import { useState } from 'react';
export default function ThemeSettings() {
const [settings, setSettings] = useState({
user: 'ada',
theme: {
mode: 'light',
colors: { primary: '#0055ff', accent: '#ff8800' },
},
});
function handlePrimaryChange(e) {
setSettings({
...settings,
theme: {
...settings.theme,
colors: {
...settings.theme.colors,
primary: e.target.value,
},
},
});
}
return (
<>
<input
type="color"
value={settings.theme.colors.primary}
onChange={handlePrimaryChange}
/>
<p>Mode: {settings.theme.mode}</p>
</>
);
}Three objects are on the path (settings, theme, colors), so there are three spreads. The pattern is mechanical, but it gets noisy fast. That is a signal to look at the options at the end of this chapter.
Changing several nested fields at once
If one event changes several fields in the same nested object, put them all in one copy. Do not call the setter several times with stale copies.
function moveTo(city, country) {
setPerson({
...person,
address: { ...person.address, city, country },
});
}This produces one new snapshot and one render. Calling setPerson twice in a row with ...person would not combine the changes, because both calls read the same person snapshot. The second call would overwrite the first. Updater functions, covered in a later chapter, are the tool for chained updates.
A single handler for many fields
Forms often have many inputs in one nested object. Computed property names let one handler serve them all:
function handleAddressChange(e) {
setPerson({
...person,
address: { ...person.address, [e.target.name]: e.target.value },
});
}Give each input a name attribute that matches a key in address, such as name="city". The square brackets tell JavaScript to use the value of e.target.name as the key, not the literal text e.target.name.
Common errors
Most nested-update bugs fall into a few groups.
| Mistake | What happens | Fix |
|---|---|---|
| `person.address.city = value` | The object is changed in place. React is never told, so nothing re-renders. | Build new objects with spread and call the setter. |
| `person.address.city = value; setPerson({ ...person })` | The screen updates, but the nested `address` object was mutated and is shared with the previous snapshot. | Copy `address` too. |
| `setPerson({ ...person, address: { city: value } })` | The `country` property is lost, because the new address has only `city`. | Spread `person.address` into the new address. |
| `{ city: value, ...person.address }` | The old value overwrites the new one. | Put the changed key after the spread. |
Why the half-fix is still a bug
The second row is the one that fools people, because it appears to work. Spreading only the top level gives React a new person, so the component re-renders and shows the new city. But person.address is the same object as before, now modified.
That causes trouble in several places:
- A child wrapped in
React.memothat receivesperson.addressas a prop compares the old and new prop by reference. They are the same object, so the child skips its render and shows a stale city. - A
useEffectoruseMemothat listsperson.addressas a dependency sees no change, and does not run. - Any older snapshot, such as one kept for an undo feature or captured by a pending handler, silently changes along with the current one.
Copying every object on the path avoids all three problems, because anything you changed has a new reference.
Reducing the pain of deep paths
If you find yourself writing four or five levels of spread, you have two common options, both covered later in this tutorial:
- Flatten the state. Restructure data so that fewer objects sit inside other objects. A flat shape needs only one spread per update.
- Use Immer. It lets you write
draft.theme.colors.primary = valueand produces the immutable copies for you.
Neither is required for shallow nesting of two levels. A two-level spread, like the city example, is clear enough to write by hand.
Exercise
State is const [order, setOrder] = useState({ id: 7, customer: { name: 'Sam', contact: { email: '[email protected]', phone: '555-0100' } } }). Write the call that changes only the email to a variable newEmail, and say how many new objects it creates.
Show answer
setOrder({ ...order, customer: { ...order.customer, contact: { ...order.customer.contact, email: newEmail } } }). It creates three new objects: the order, the customer, and the contact. The id, the name, and the phone values are reused unchanged.
Exercise
A teammate writes setPerson({ ...person, address: { city: e.target.value } }) and reports that the country disappears after typing in the city box. What is wrong, and what is the fix?
Show answer
The new address object contains only city, so country is dropped. Spread the old address first: address: { ...person.address, city: e.target.value }.