AceDevHub
Modern PatternsFree

structuredClone and Immutability

Copy nested data safely with structuredClone, understand shallow vs deep copies, and update state without accidental mutation.

IntermediateFreeData

Reference semantics mean assignment never copies nested objects. Spread and Object.assign clone one level — nested objects are still shared. React and modern state libraries expect updates that replace changed branches without mutating previous state (for cheap change detection). structuredClone is the built-in deep clone for structured data; knowing its limits prevents production data corruption.

Shallow copy — spread and slice

Shallow copy duplicates the top container — new array or object — but nested references point to the same inner objects. Fine when data is flat or you only replace top-level fields. Breaks when you clone state, mutate nested field on copy, and accidentally mutate previous state too.

shallow-copy.js
Loading editor…
Outputconsole
Changed
['js']

structuredClone — built-in deep clone

structuredClone(value) deep-copies most structured-cloneable types: objects, arrays, Dates, Maps, Sets, ArrayBuffers, and more. It does not clone functions, DOM nodes, or symbols. It handles cycles (objects that reference themselves). Prefer it over JSON.parse(JSON.stringify(x)) which drops undefined, functions, Dates become strings, and fails on BigInt.

structured-clone.js
Loading editor…
Outputconsole
['admin']
true
string

Immutable update patterns

Instead of mutating, return new objects with changed branches. Update one field: { ...user, name: "New" }. Update nested field: { ...user, profile: { ...user.profile, theme: "light" } }. Arrays: map to replace one item, filter to remove, spread to append. Libraries like Immer hide this boilerplate but the underlying rule stays: new reference at the level that changed.

immutable-update.js
Loading editor…
Outputconsole
2
3

Immutable updates feel verbose but enable React memoization, time-travel debugging, and cheap change detection via reference equality. When only one field changes, reuse unchanged branches from the previous tree. structuredClone is for snapshots and worker postMessage — not a substitute for immutable update patterns in UI state.

When not to clone

Deep cloning large trees on every keystroke destroys performance. Immutable updates target the smallest changed branch; structuredClone suits snapshots before undo, worker handoff, or serializing state for postMessage. Profile clone cost before cloning entire Redux stores each action.


  1. 1Spread clones one level — nested refs shared
  2. 2structuredClone for deep copy of plain data trees
  3. 3Avoid JSON clone for Dates, undefined, BigInt
  4. 4Immutable updates: new object/array at changed branch
  5. 5Next lesson: JavaScript best practices capstone