Sub topic 10
Structural Sharing: Copy Only What Changes
This chapter assumes you can already write nested immutable updates with spread syntax, and that you know structuredClone makes a full deep copy. Here we look at what those nested updates produce in memory. The new state reuses most of the old one. That reuse is called structural sharing, and it is the reason immutable updates stay affordable on large state trees.
The Core Idea
Structural sharing means that a new version of a data structure points to the same objects as the old version everywhere nothing changed. You copy only the objects on the path from the root to the value you changed. Every other branch is shared by reference.
Take a state tree with a user branch and a settings branch. If you change user.address.city, these objects need new copies:
- The root object, because one of its properties (
user) now points somewhere new. user, because itsaddressproperty now points somewhere new.address, because itscityvalue changed.
settings is not on that path, so both versions point to the same settings object.
The cost of an update depends on the depth of the change and the width of each copied object. The total size of the tree does not matter. A tree with 50,000 nodes and a change three levels deep still copies only three objects.
Path Copying as a Reusable Function
The nested spread pattern from the earlier chapter is path copying written by hand. Writing it as a general helper makes the mechanism clear:
function setIn(obj, path, value) {
if (path.length === 0) return value;
const [key, ...rest] = path;
const current = obj?.[key];
const childBase = rest.length > 0 && current == null ? {} : current;
const nextChild = setIn(childBase, rest, value);
// No-op update: keep the original reference so sharing is preserved.
if (Object.is(nextChild, current)) return obj;
const copy = Array.isArray(obj) ? [...obj] : { ...obj };
copy[key] = nextChild;
return copy;
}
const state = {
user: { name: 'Ada', address: { city: 'London' } },
settings: { theme: 'dark' },
todos: [{ id: 1, done: false }, { id: 2, done: false }]
};
const next = setIn(state, ['todos', 1, 'done'], true);
console.log(next.todos[1].done); // true
console.log(state.todos[1].done); // false
console.log(next.user === state.user); // true, shared
console.log(next.settings === state.settings); // true, shared
console.log(next.todos[0] === state.todos[0]); // true, shared
console.log(next.todos === state.todos); // false, on the path
const same = setIn(state, ['user', 'name'], 'Ada');
console.log(same === state); // true, nothing changedThe function does three things you should copy into hand-written updates:
- It copies one level at a time with a shallow copy, so only the nodes on the path become new.
- It keeps arrays as arrays (
[...obj]) and objects as objects ({ ...obj }). - It returns the original reference when the new value equals the old one. A no-op update produces no new objects, so nothing downstream sees a change.
Seeing What Is Shared
You can check sharing directly. This helper walks two versions and lists the paths where both point to the same object:
function sharedPaths(prev, next, path = '') {
const isObj = v => v !== null && typeof v === 'object';
if (!isObj(prev) || !isObj(next)) return [];
if (prev === next) return [path || '(root)'];
const result = [];
for (const key of Object.keys(next)) {
const childPath = path ? `${path}.${key}` : key;
result.push(...sharedPaths(prev[key], next[key], childPath));
}
return result;
}
const prev = {
user: { name: 'Ada', address: { city: 'London' } },
settings: { theme: 'dark', layout: { columns: 2 } }
};
const updated = {
...prev,
user: { ...prev.user, address: { ...prev.user.address, city: 'Paris' } }
};
console.log(sharedPaths(prev, updated)); // [ 'settings' ]The helper reports settings and stops there, because everything below a shared object is shared too. This is a quick way to confirm that an update copies only what it should.
Comparing the Copying Strategies
| Strategy | Objects created per update | Unchanged branches | Old version safe? |
|---|---|---|---|
| Mutate in place | 0 | Same objects (only one version exists) | No |
| Deep clone, then mutate | Every object in the tree | All new copies | Yes |
| Path copying (structural sharing) | One per level on the changed path | Shared by reference | Yes, if no one mutates shared nodes |
Deep cloning and structural sharing both leave the old version intact. Deep cloning costs time proportional to the whole tree. It also gives every node a new identity, so every consumer thinks everything changed. Structural sharing costs time proportional to the changed path, and node identity tells you exactly which branches changed. The next chapter uses that identity for change detection.
Memory and Garbage Collection
A version history built with structural sharing costs much less memory than you might expect. If you keep 100 past states for undo, and each update changed one path of three objects, the history holds about 300 extra objects. It does not hold 100 full trees.
When you drop a reference to an old version, the garbage collector frees only the nodes that no other version still uses. Shared nodes stay alive as long as any version points to them. You don't manage this yourself. It follows from ordinary reachability.
Edge Cases and Common Errors
Mutating a shared node corrupts every version
Sharing is only safe if nobody mutates the shared objects. One mutation reaches every version that holds that node:
const v1 = { settings: { theme: 'dark' }, count: 0 };
const v2 = { ...v1, count: 1 };
v2.settings.theme = 'light'; // mutation of a shared node
console.log(v1.settings.theme); // 'light', the "old" version changed tooThis is the reason to pair structural sharing with discipline, freezing in development, or a tool like Immer, which is covered later.
Copying too much breaks sharing
A common mistake is copying every item "to be safe":
const todos = [{ id: 1, done: false }, { id: 2, done: false }];
// Breaks sharing: every item gets a new identity.
const bad = todos.map(t => (t.id === 2 ? { ...t, done: true } : { ...t }));
// Preserves sharing: unchanged items are returned as they are.
const good = todos.map(t => (t.id === 2 ? { ...t, done: true } : t));
console.log(bad[0] === todos[0]); // false
console.log(good[0] === todos[0]); // trueThe bad version is still correct as data. It wastes allocations, though, and it makes reference checks report changes that did not happen. In a UI framework, every list item would re-render.
No-op updates should return the same reference
Writing { ...state, filter: state.filter } creates a new root even though no value changed. Check before copying when the update might be a no-op, as setIn does with Object.is. Reducers and selectors that return a fresh object on every call cause the same false "changed" signal.
Wide nodes are expensive to copy
Path copying makes a shallow copy of each node on the path, and a shallow copy costs time proportional to the number of keys or elements in that node. Updating one item in an array of 100,000 elements copies 100,000 references, even though only one item changed. Depth is cheap; width is not. If you have large flat collections that change often, consider these options:
- Normalize the collection into an object keyed by ID, split into smaller groups.
- Use a persistent data structure, which splits large collections into small internal nodes so an update copies only a few of them. A later chapter covers this.
Serialization destroys sharing
JSON.parse(JSON.stringify(state)) and structuredClone(state) both produce a tree where nothing is shared with the original. Use them when you need a fully independent copy, for example before sending data to code you don't trust. Don't use them as an update step. Be aware that structuredClone keeps sharing inside the cloned tree, so two references to one object stay one object in the clone, but the clone shares nothing with the source.
When Structural Sharing Fits
Use structural sharing as the default for application state that changes in small pieces: UI state, reducer state, document models, and caches. Prefer a full deep copy when you need an isolated snapshot that will be mutated freely, such as a scratch copy for an algorithm or data passed to a worker. Prefer in-place mutation for local, short-lived data that no other code can see, such as an array you build inside one function and return.
Exercise
Given const s = { a: { b: { c: 1 } }, d: { e: 2 }, f: [1, 2, 3] }, you run const t = { ...s, a: { ...s.a, b: { ...s.a.b, c: 5 } } }. Which of these are true: t.d === s.d, t.f === s.f, t.a === s.a, t.a.b === s.a.b?
Show answer
t.d === s.d and t.f === s.f are true because those branches are not on the changed path and are shared. t.a === s.a and t.a.b === s.a.b are false because a and b are on the path to c and were copied.
Exercise
A reducer handles a "mark all done" action with state.todos.map(t => ({ ...t, done: true })). When all todos are already done, what goes wrong, and how do you fix it?
Show answer
Every todo gets a new object and the array gets a new identity, so reference checks report changes that did not happen, and every item looks updated. Fix it by returning t unchanged when t.done is already true, and by returning the original state when no todo changed, for example by checking state.todos.every(t => t.done) first.
Exercise
You update one item in an array of 200,000 records using path copying. Why is this slower than updating a value three levels deep in a small object, and what are two ways to reduce the cost?
Show answer
Path copying shallow-copies every node on the path, and copying the array copies all 200,000 references, so the cost scales with the width of the node. Two fixes: split or normalize the collection into smaller keyed groups so each copied node is small, or use a persistent data structure that stores the collection as a tree of small nodes so an update copies only a few of them.