Sub topic 10
Structural Sharing: Copy Only What Changes
This chapter assumes you already know how to make shallow copies with spread, how to update nested data immutably, and how structuredClone makes deep copies. Here we look at what those nested updates leave behind in memory, and why that matters.
The Working Model
Structural sharing means that a new version of your data reuses every part of the old version that did not change. When you update one deep property, you copy only the objects on the path from the root down to that property. Every other branch is the same object in memory, referenced by both the old and the new version.
A deep clone takes the opposite approach. It copies everything, including the branches you never touched.
A Reusable Path Update
The helper below writes a value at a path and copies only the containers along that path. It also returns the original object when the value is already there, so an update that changes nothing allocates nothing.
function setIn(obj, [key, ...rest], value) {
if (key === undefined) return value;
const current = obj == null ? {} : obj;
const child = setIn(current[key], rest, value);
if (child === current[key]) return current; // no change, reuse as-is
if (Array.isArray(current)) {
const copy = current.slice();
copy[key] = child;
return copy;
}
return { ...current, [key]: child };
}
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.todos === state.todos); // false, on the path
console.log(next.todos[0] === state.todos[0]); // true, shared
console.log(next.user === state.user); // true, shared
console.log(next.settings === state.settings); // true, shared
const same = setIn(state, ['user', 'name'], 'Ada');
console.log(same === state); // true, nothing changedWhat It Costs
An update costs one shallow copy for each level of the path. Each copy costs time in proportion to how many keys or elements that container holds. The size of the untouched branches does not affect the cost.
| Approach | Work per update | Memory per version | Unchanged branches |
|---|---|---|---|
| Mutation in place | Constant | None | Same objects, but old version is lost |
| Deep clone, then mutate | Whole tree | Whole tree | New objects everywhere |
| Structural sharing | Containers on the path | Containers on the path | Same objects, old version intact |
For a state tree with thousands of entries, a single update with structural sharing might copy three or four small objects. A deep clone would copy all of them.
Common Errors
- Mutating a shared branch. The old and new versions hold the same object for every untouched branch. If you write
next.settings.theme = 'light', the change also shows up instate. Structural sharing is only safe if nothing mutates. That is one reason to freeze state during development. - Copying unconditionally. If your update always spreads, even when the value is unchanged, you get a new object each time. Any code that compares references then sees a change that did not happen.
- Deep cloning "to be safe". Calling
structuredClonebefore every update throws away the sharing and turns every shared branch into a new reference. - Forgetting arrays. If you spread an array into an object (
{ ...arr }), you get an object with numeric keys. Copy arrays withslice(), spread into[], orwith().
Because unchanged branches keep their identity, you can tell what changed by comparing references with ===. The next chapter builds on that.
Exercise
Using setIn from this chapter, you run const next = setIn(state, ['user', 'address', 'city'], 'Paris'). Which of these are true: next.user === state.user, next.user.address === state.user.address, next.settings === state.settings, next.todos === state.todos?
Show answer
Only next.settings === state.settings and next.todos === state.todos are true. The root, user, and address sit on the update path, so each is copied. The settings and todos branches are off the path and are shared.
Exercise
A teammate's update function always returns { ...state, filter: newFilter }, even when newFilter equals state.filter. What problem does this cause, and how do you fix it?
Show answer
The function returns a new root object even when nothing changed, so reference checks report a change that did not happen and can trigger needless work. Fix it by returning state unchanged when newFilter === state.filter.