Sub topic 4
Updating objects with the spread operator
This chapter assumes you know JavaScript objects and the spread operator, can write a React function component with useState, and can handle events such as onChange. It covers how to update object state by building a new object, where shallow copies stop helping, and the errors people hit most often.
Why a new object is required
React treats state as a snapshot. When you call a setter, React compares the new value with the one it already holds. If it is the same reference, React has nothing new to render. It may skip the update entirely.
Mutating an object edits it in place. The reference stays the same, so passing it back to the setter looks like "no change". Even when a mutation seems to work, the result is unreliable. The current render's snapshot has already been captured, and effects, memoized children, and React.memo comparisons all rely on reference changes to detect updates.
The rule is simple: treat state objects as read-only, and give the setter a new object whenever anything changes.
Copying with spread
Object spread copies the own enumerable properties of one object into another. Placing it inside an object literal gives you a new object. Properties written after the spread override the copied ones.
import { useState } from 'react';
export default function Form() {
const [person, setPerson] = useState({
firstName: 'Ada',
lastName: 'Lovelace',
});
function handleFirstNameChange(e) {
// Wrong: person.firstName = e.target.value; setPerson(person);
// The setter receives the same object, so React sees no change.
setPerson({ ...person, firstName: e.target.value });
}
function handleLastNameChange(e) {
setPerson({ ...person, lastName: e.target.value });
}
return (
<>
<label>
First name:
<input value={person.firstName} onChange={handleFirstNameChange} />
</label>
<label>
Last name:
<input value={person.lastName} onChange={handleLastNameChange} />
</label>
<p>
{person.firstName} {person.lastName}
</p>
</>
);
}In handleFirstNameChange, ...person copies firstName and lastName. The explicit firstName: e.target.value that follows replaces the copied first name. The order matters, as the table shows.
| Expression | Result for `person = { firstName: 'Ada', lastName: 'Lovelace' }` |
|---|---|
| `{ ...person, firstName: 'Grace' }` | `{ firstName: 'Grace', lastName: 'Lovelace' }` |
| `{ firstName: 'Grace', ...person }` | `{ firstName: 'Ada', lastName: 'Lovelace' }` (the override is lost) |
One handler for many fields
When a form has many fields, you can use a computed property name so one handler covers all of them. Give each input a name that matches a key in state.
import { useState } from 'react';
export default function ProfileForm() {
const [person, setPerson] = useState({
firstName: 'Ada',
lastName: 'Lovelace',
email: '[email protected]',
});
function handleChange(e) {
setPerson({
...person,
[e.target.name]: e.target.value,
});
}
return (
<>
<input name="firstName" value={person.firstName} onChange={handleChange} />
<input name="lastName" value={person.lastName} onChange={handleChange} />
<input name="email" value={person.email} onChange={handleChange} />
</>
);
}The square brackets tell JavaScript to use the value of e.target.name as the key. This is a plain JavaScript feature, not a React one.
Spread makes a shallow copy
Spread copies one level. Each property of the new object holds the same value as in the old one. For numbers and strings that value is the data itself. For an object or an array, the value is a reference, so the old and new objects point to the same nested object.
const original = { name: 'Ada', address: { city: 'London' } };
const copy = { ...original };
console.log(copy === original); // false
console.log(copy.address === original.address); // trueThe top-level objects differ, but address is shared. If you write copy.address.city = 'Paris', you also change original.address.city. That is a mutation of state, with the same problems as before.
Updating nested objects
To change a nested value, copy every object on the path from the root to that value. Objects off the path can be reused as they are.
import { useState } from 'react';
export default function AddressForm() {
const [person, setPerson] = useState({
name: 'Ada',
address: { city: 'London', country: 'UK' },
});
function handleCityChange(e) {
setPerson({
...person,
address: { ...person.address, city: e.target.value },
});
}
return (
<>
<input value={person.address.city} onChange={handleCityChange} />
<p>
{person.name} lives in {person.address.city}, {person.address.country}.
</p>
</>
);
}Here two spreads are needed. The outer one copies name and replaces address. The inner one copies country and replaces city. The result is a new person and a new address, while every other value is reused.
Every extra level of nesting adds another spread, and the code gets harder to read. The later chapters on flat state and Immer address that.
Updates that depend on previous state
A handler sometimes calls the setter more than once, or you want the newest queued value rather than the one captured in this render. In that case pass an updater function. React calls it with the latest pending state and uses what it returns.
function handleBirthday() {
setPerson((prev) => ({ ...prev, age: prev.age + 1 }));
setPerson((prev) => ({ ...prev, age: prev.age + 1 }));
}Both calls count, so age goes up by 2. With setPerson({ ...person, age: person.age + 1 }) twice, both calls read the same snapshot of person, and age goes up by 1. A later chapter covers updater functions in full. For a single update from an input event, passing the new object directly is fine.
Common errors
- Mutating, then setting.
person.age = 31; setPerson(person);keeps the same reference. Build a new object instead. - Spreading in the wrong order. Put overrides after the spread.
- Forgetting a level.
setPerson({ ...person, address: { city: 'Paris' } })dropscountry, because the inner object was built without spreadingperson.address. - Mutating a nested object and spreading the parent.
person.address.city = 'Paris'; setPerson({ ...person });produces a new top-level object, so the screen may update. But you have still changed the old snapshot. Anything holding the earlierperson, such as a memoized child or a history list, now sees the edit. - Expecting a deep copy. Spread never clones nested objects. Libraries or
structuredClonecan, but copying everything on each keystroke is usually wasteful. - Copying class instances. Spread copies own properties only, not the prototype. A
Dateor class instance spread into an object literal loses its methods. Keep such values as plain data in state, or create a new instance.
Exercise
State is { user: { name: 'Sam', prefs: { theme: 'light', lang: 'en' } } } held in const [state, setState] = useState(...). Write the setter call that changes theme to 'dark' without mutating anything and without losing name or lang.
Show answer
setState({ ...state, user: { ...state.user, prefs: { ...state.user.prefs, theme: 'dark' } } }); Each object on the path (state, user, prefs) is copied with spread, and only theme is overridden last.
Exercise
A handler runs setPerson({ firstName: e.target.value, ...person }). Typing in the input changes nothing on screen. Why, and how do you fix it?
Show answer
The spread comes after the override, so the old firstName from person overwrites the new value. Move the spread first: setPerson({ ...person, firstName: e.target.value }).