Sub topic 3
Deep Copies with structuredClone
This chapter assumes you already know shallow copying with spread syntax and how to update nested data immutably. It also assumes you can install npm packages and use ES modules.
Deep Copies with structuredClone
structuredClone copies every level of a value. It also keeps built-in types such as Date, Map, and Set, which JSON.parse(JSON.stringify(x)) loses.
const original = { created: new Date(0), items: [{ id: 1 }] };
const clone = structuredClone(original);
clone.items[0].id = 99;
console.log(original.items[0].id); // 1
console.log(clone.created instanceof Date); // trueStructural Sharing: Copy Only What Changes
A deep clone copies everything, even data that did not change. Structural sharing copies only the objects along the path to the change and reuses every other branch. A nested spread update already does this.
Cheap Change Detection with Reference Equality
Immutable updates replace every object that changes, so a === b tells you whether anything inside it changed. That check takes constant time, while a deep comparison has to walk the whole structure. React's memo and Redux selectors depend on this check.
let lastInput, lastOutput;
function selectDone(todos) {
if (todos === lastInput) return lastOutput; // unchanged, reuse the result
lastInput = todos;
lastOutput = todos.filter(t => t.done);
return lastOutput;
}Writing Immutable Updates with Immer
Immer's produce gives you a draft that you can mutate. It records your changes and returns a new state with structural sharing. In development it also freezes the result automatically.
import { produce } from 'immer';
const state = { todos: [{ id: 1, text: 'Write', done: false }] };
const next = produce(state, draft => {
draft.todos[0].done = true;
});
console.log(state.todos[0].done); // false
console.log(next.todos[0].done); // truePersistent Data Structures and Immutable.js
Immutable.js provides its own Map and List types, built on hash array mapped tries. A trie shares internal nodes between versions, so an update on a large collection stays cheap. The cost is that you need get, set, and toJS() to move data between these types and plain objects.
Choosing an Approach: Performance and Design Trade-offs
| Approach | Best for | Cost |
|---|---|---|
| Spread and non-mutating methods | Small, shallow updates | Verbose for deep nesting |
| structuredClone | Isolated snapshots | Copies everything, so `===` change checks no longer work |
| Immer | Deep updates in app state | Proxy overhead, one dependency |
| Immutable.js | Very large, frequently updated collections | Non-standard API, conversion cost |
Exercise
You deep-clone your Redux state with structuredClone before each update. Why do memoized selectors stop skipping work?
Show answer
structuredClone creates a new reference for every object, including unchanged branches. Every === check fails, so every selector recomputes. Use spread or Immer instead, so unchanged branches stay shared.