Sub topic 5
Spread makes a shallow copy
This chapter assumes you know JavaScript objects and arrays, the spread operator, and the useState hook. It also assumes you have seen an event handler that calls a state setter. The previous chapter showed how { ...person, firstName: 'Grace' } builds a new object. Here you will look at what that copy contains and what it shares with the original.
What a shallow copy is
Spread copies the properties found directly on the object. It does not copy the objects those properties point to.
Each property holds a value. If the value is a primitive (string, number, boolean, null, undefined), the copy gets its own independent value. If the value is an object, array, or function, the copy gets the same reference. Both the original and the copy then point at one shared 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.name === original.name); // true: equal strings
console.log(copy.address === original.address); // true: the same nested objectOnly the outer object is new. The address object exists once, and both original.address and copy.address refer to it.
Why this matters for state
React decides whether to re-render by comparing the new state value with the previous one using Object.is. A new top-level object passes that check. So a shallow copy is enough to trigger a render.
The trouble is that the shared nested object is also part of the previous snapshot. If you change it, you change the old state and the new state at once.
import { useState } from 'react';
export default function Profile() {
const [person, setPerson] = useState({
name: 'Ada',
address: { city: 'London', country: 'UK' },
});
function handleCityChange(e) {
// Wrong: the spread copy still shares person.address
const next = { ...person };
next.address.city = e.target.value; // mutates the old state's address too
setPerson(next);
}
return (
<label>
City:
<input value={person.address.city} onChange={handleCityChange} />
</label>
);
}This often appears to work, because the new top-level object triggers a render and the render reads the mutated value. That is why the bug survives casual testing. It breaks in less obvious places:
- Any earlier snapshot, such as a saved "previous value" for undo, now shows the new city.
- A child wrapped in
React.memothat receivesperson.addressas a prop sees the same reference. It compares equal and skips rendering, so it shows stale data. - Hooks that depend on
person.address, such asuseEffectoruseMemo, do not see a changed dependency and do not re-run. - In Strict Mode, React runs some updates twice in development. Mutation can then be applied twice and produce wrong results.
Seeing the sharing directly
You can check this outside React with plain JavaScript. Keep a reference to the old state and watch it change.
const before = {
name: 'Ada',
address: { city: 'London', country: 'UK' },
};
const after = { ...before };
after.name = 'Grace'; // safe: replaces a primitive on the copy
after.address.city = 'Paris'; // unsafe: edits the shared object
console.log(before.name); // 'Ada' (unchanged)
console.log(before.address.city); // 'Paris' (changed by accident)Reassigning after.name touches only the copy, because name belongs to that object. Writing after.address.city first reads after.address, which is the shared object, and then modifies it. The assignment goes through the reference, so it reaches the original.
The rule: copy every level you change
To change a value at depth N, you create a new object at every level from the top down to that value. Levels you do not touch can stay shared, and that is fine because nobody modifies them.
import { useState } from 'react';
export default function Profile() {
const [person, setPerson] = useState({
name: 'Ada',
address: { city: 'London', country: 'UK' },
tags: ['math', 'poetry'],
});
function handleCityChange(e) {
setPerson({
...person, // copy level 1
address: { ...person.address, city: e.target.value }, // copy level 2
});
}
return (
<label>
City:
<input value={person.address.city} onChange={handleCityChange} />
</label>
);
}After this update, person.tags is still the same array as before. That is intentional and correct. Because tags did not change, a memoized child that receives person.tags sees an equal reference and correctly skips re-rendering. Sharing untouched branches is a benefit of this approach, sometimes called structural sharing.
The next chapter walks through nested updates in more detail. For now, the point is that the number of spreads you write matches the depth of the change.
Arrays are shallow too
Spreading an array has the same property. [...items] makes a new array, but the elements are the same references.
const items = [
{ id: 1, title: 'Write' },
{ id: 2, title: 'Edit' },
];
const copy = [...items];
console.log(copy === items); // false
console.log(copy[0] === items[0]); // true: same object
copy[0].title = 'Draft'; // mutates the object that items also holds
console.log(items[0].title); // 'Draft'So copying the array protects you from push, splice, sort, and reverse on the copy. It does not protect the objects inside. If you want to change one element, replace it with a new object, for example with map and { ...item, title: 'Draft' }.
Other shallow copy tools
Several common ways to copy are shallow in exactly the same manner.
| Technique | Result | Depth |
|---|---|---|
| `{ ...obj }` | New object | Shallow |
| `Object.assign({}, obj)` | New object | Shallow |
| `[...arr]` | New array | Shallow |
| `arr.slice()` | New array | Shallow |
| `arr.map((x) => x)` | New array | Shallow |
| `structuredClone(value)` | Deep copy | Deep |
structuredClone makes a deep copy, but it fails on functions and some other values, and it copies everything, including branches you did not change. Cloning the entire state on each update is usually the wrong tool for state. It breaks reference equality for untouched parts, so memoized children re-render needlessly. Prefer copying only the path you change.
Edge cases
- Spread order matters. In
{ ...person, name: 'Grace' }, the laternameoverrides the one fromperson. Reversing the order,{ name: 'Grace', ...person }, lets the old value win. - Only own, enumerable properties are copied. Spread skips inherited properties and non-enumerable ones. It also drops the prototype, so a class instance becomes a plain object without its methods. Keep class instances out of state, or store plain data.
Date,Map, andSetdo not copy with spread.{ ...new Map() }gives an empty object. Build new ones explicitly, such asnew Map(oldMap).- Spreading
nullorundefinedis safe in object spread.{ ...undefined }gives{}. Spreading a non-iterable into an array literal throws aTypeError. - Frozen objects.
Object.freezeis itself shallow. A frozen object's nested objects can still be mutated unless you freeze them too.
How to spot the bug in review
When you read an update handler, ask one question: for each assignment, what object does the left-hand side belong to? A statement like next.address.city = ... writes into next.address, which came from the old state. Any assignment with two or more dots on the left is a signal to check whether each intermediate object was copied.
Another common sign is a nested copy that looks correct but only goes one level deep, for instance { ...person, address: person.address }. That line reuses the old address and gives you nothing for the nested level.
Exercise
A component holds const [form, setForm] = useState({ title: 'Draft', meta: { views: 0, flags: ['new'] } });. A handler runs const next = { ...form }; next.meta.views = next.meta.views + 1; setForm(next);. The screen updates, but a React.memo child that receives form.meta never updates. Explain why, and write a corrected handler.
Show answer
The spread copies only the top level, so next.meta is the same object as form.meta. The handler mutates that shared object and then passes a new top-level object. React re-renders the parent, but the memoized child receives the same meta reference as before and skips rendering. Corrected handler: setForm({ ...form, meta: { ...form.meta, views: form.meta.views + 1 } });. This creates a new meta object, so the child sees a changed prop. The flags array stays shared, which is fine because it was not changed.
Exercise
Given const a = { n: 1, list: [1, 2] }; const b = { ...a }; b.n = 5; b.list.push(3);, what are a.n and a.list afterward?
Show answer
a.n is still 1, because n is a primitive and b has its own copy. a.list is [1, 2, 3], because b.list and a.list are the same array and push mutated it.