Sub topic 9
Updating objects in state
This chapter assumes you can write function components, use useState with event handlers, and read spread syntax ({ ...obj }) and computed property names ({ [key]: value }). It covers how to change one field of an object held in state, and why the way you do it matters.
Why you cannot mutate the object
State can hold any JavaScript value, including objects. React does not watch the properties inside an object. When you call a setter, React compares the new value with the current one using Object.is. If they are the same reference, React treats the update as "nothing changed" and skips the re-render.
Here is the mistake in code:
import { useState } from 'react';
function BrokenProfile() {
const [person, setPerson] = useState({ name: 'Ada', city: 'London' });
function handleCity(e) {
person.city = e.target.value; // mutates the existing object
setPerson(person); // same reference, so React bails out
}
return (
<>
<input value={person.city} onChange={handleCity} />
<p>{person.name} lives in {person.city}</p>
</>
);
}Typing in the input appears to do nothing. The object was changed, but React never re-rendered. Even if another update later triggers a render, mutation breaks the snapshot model from the previous chapters: older handlers and memoized children can see data that changed behind their back.
The rule is to treat state objects as read-only. To change something, build a new object and pass it to the setter.
Copying with spread
Spread copies the properties of the old object into a new one. Properties written after the spread override the copied ones.
import { useState } from 'react';
function Profile() {
const [person, setPerson] = useState({ name: 'Ada', city: 'London' });
return (
<>
<input
value={person.city}
onChange={e => setPerson({ ...person, city: e.target.value })}
/>
<p>{person.name} lives in {person.city}</p>
</>
);
}Order matters. { city: 'Paris', ...person } would let the old city overwrite the new one.
A setter for an object does not merge. Unlike the setState of class components, setPerson({ city: 'Paris' }) replaces the whole object, and name is gone. If you forget the spread, fields silently disappear.
One handler for many fields
Controlled forms often have several fields. Give each input a name that matches a property and use a computed key:
import { useState } from 'react';
function ProfileForm() {
const [person, setPerson] = useState({
name: '',
email: '',
subscribed: false,
});
function handleChange(e) {
const { name, type, value, checked } = e.target;
setPerson({
...person,
[name]: type === 'checkbox' ? checked : value,
});
}
return (
<form>
<input name="name" value={person.name} onChange={handleChange} />
<input name="email" value={person.email} onChange={handleChange} />
<label>
<input
type="checkbox"
name="subscribed"
checked={person.subscribed}
onChange={handleChange}
/>
Subscribe
</label>
</form>
);
}Checkboxes use checked, not value, so the handler branches on type. The event properties are destructured before the setter is called. That habit matters in the next section.
Updating from the previous object
Spread reads person from the current render's snapshot. If one handler updates the same object twice, the second call starts from the same stale snapshot and overwrites the first:
import { useState } from 'react';
function Reset() {
const [person, setPerson] = useState({ name: 'Ada', city: 'London' });
function resetWrong() {
setPerson({ ...person, name: '' });
setPerson({ ...person, city: '' }); // still spreads the old name
}
function reset() {
setPerson(p => ({ ...p, name: '' }));
setPerson(p => ({ ...p, city: '' }));
}
return (
<>
<p>{person.name || '(no name)'} / {person.city || '(no city)'}</p>
<button onClick={resetWrong}>Reset (only city clears)</button>
<button onClick={reset}>Reset</button>
</>
);
}The updater form p => ({ ...p, ... }) receives the latest pending state, so both changes survive. Use it whenever one event produces several updates to the same object, or when the update runs later, such as in a timeout.
When you use an updater in an input handler, read the value from the event first:
function handleChange(e) {
const { name, value } = e.target;
setPerson(p => ({ ...p, [name]: value }));
}The updater may run after the handler returns, so do not depend on e inside it.
Nested objects
Spread is shallow. It copies one level, and nested objects are shared between the old and new copies. To change a nested field, copy every level on the path to it:
import { useState } from 'react';
function Settings() {
const [user, setUser] = useState({
name: 'Ada',
address: { city: 'London', zip: 'N1' },
});
function setCity(city) {
setUser({
...user,
address: { ...user.address, city },
});
}
return (
<>
<input value={user.address.city} onChange={e => setCity(e.target.value)} />
<p>{user.name}, {user.address.city} {user.address.zip}</p>
</>
);
}Writing setUser({ ...user, address: { city } }) would drop zip. Writing user.address.city = city would mutate an object shared with the previous snapshot.
Objects you did not touch keep their identity. Here user.address.zip is copied by value, and any untouched nested object would be reused by reference. That is correct and cheap, and it lets React.memo skip children whose props did not change.
Mutation is fine for objects you just created
Only objects that already live in state are off limits. This is safe, because next is brand new and nothing else has seen it:
function setCity(city) {
const next = { ...user, address: { ...user.address } };
next.address.city = city;
setUser(next);
}The danger is the shallow copy: if you wrote const next = { ...user } and then next.address.city = city, you would mutate the shared nested object.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Input does not update | Mutated the object and passed the same reference | Pass a new object |
| Other fields vanish | Passed a partial object, expecting a merge | Spread the old object first |
| New value is overwritten | Spread placed after the override | Put overrides after the spread |
| Second update in one handler is lost | Both spread the same snapshot | Use `p => ({ ...p, ... })` |
| Nested value changes but a memoized child does not update | Shallow copy shared the nested object | Copy each level on the path |
Deep structures
If nested updates become noisy, first ask whether the state can be flatter, as the later chapter on state shape discusses. If it cannot, a library such as Immer lets you write mutating-style code against a draft and produces an immutable result. structuredClone(obj) makes a deep copy, but it copies everything on every change, so use it sparingly on large objects.
Exercise
A component holds const [form, setForm] = useState({ title: '', meta: { author: 'Ada', tags: 2 } }). Write the call that sets meta.author to 'Grace' while keeping title and meta.tags, and explain why setForm({ ...form, meta: { author: 'Grace' } }) is wrong.
Show answer
Use setForm({ ...form, meta: { ...form.meta, author: 'Grace' } }), or setForm(f => ({ ...f, meta: { ...f.meta, author: 'Grace' } })) if other updates are queued. The wrong version replaces meta with an object that has only author, so tags is lost. Spread copies one level only, so each level on the path needs its own spread.
Exercise
Why does person.name = 'Grace'; setPerson(person); usually leave the screen unchanged?
Show answer
The setter receives the same object reference. React compares old and new state with Object.is, finds them equal, and skips the re-render, even though a property was changed.