Sub topic 5
Spread Makes a Shallow Copy
This chapter assumes you know JavaScript objects, arrays, and the spread operator, plus basic useState in function components. You have already seen that setPerson({ ...person, firstName: 'Grace' }) replaces state with a new object. Here you will see what that copy contains and where it stops.
What "shallow" means
Spread copies the properties of an object one level deep. Each property value is copied as it is. If the value is a number, string, or boolean, you get an independent copy. If the value is an object or array, you copy the reference, which is the pointer to the same object in memory.
const original = {
name: 'Ada',
address: { city: 'London', country: 'UK' },
};
const copy = { ...original };
console.log(copy === original); // false: a new top-level object
console.log(copy.address === original.address); // true: same nested objectThe top-level object is new. The address object is shared by both.
The bug this causes
If you change a nested value through the copy, the original changes too.
const original = {
name: 'Ada',
address: { city: 'London', country: 'UK' },
};
const copy = { ...original };
copy.address.city = 'Paris';
console.log(original.address.city); // 'Paris'In React this is a mutation of state, even though you used spread. The address object that state holds was changed in place, so the problems from the earlier chapters return. The same applies to arrays: [...todos] gives you a new array, but the objects inside it are the same objects.
// Wrong: the new array holds the same todo objects.
const next = [...todos];
next[0].done = true; // mutates a todo that state still references
setTodos(next);The rule: copy every level you change
To change a nested value, copy each object on the path from the top of state down to that value. Objects you do not change can be shared safely, because nobody mutates them.
import { useState } from 'react';
function Profile() {
const [person, setPerson] = useState({
name: 'Ada',
address: { city: 'London', country: 'UK' },
});
function handleCityChange(e) {
setPerson({
...person, // copy level 1
address: { ...person.address, city: e.target.value }, // copy level 2
});
}
return (
<input value={person.address.city} onChange={handleCityChange} />
);
}
export default Profile;The new person and the new address are fresh objects. person.name is a string, so it needs no further copying. Any other nested object you did not touch would stay shared, and that is fine.
Common errors
| Mistake | Why it fails | Fix |
|---|---|---|
| `setPerson({ ...person }); ` after editing `person.address.city` | The edit already mutated shared state | Copy `address` and set the new value in the copy |
| `[...items]` then `next[i].done = true` | The array is new, the item is not | Use `map` and return `{ ...item, done: true }` |
| Assuming `{ ...a }` is a deep copy | Spread only copies one level | Copy each level you change |
Exercise
State is { title: 'Trip', settings: { theme: 'dark', notify: true } }. Write the setter call that changes theme to 'light' without mutating state, and say which objects in the new state are shared with the old state.
Show answer
setForm({ ...form, settings: { ...form.settings, theme: 'light' } }). The top-level object and the settings object are new. The strings title, notify, and any other values are copied by value, so nothing else is shared. If settings held another nested object, the new settings would share it with the old one.