structuredClone() and Immutable Update Patterns in WordPress JavaScript

structuredClone(): real deep copies in WordPress JavaScript

The spread operator copies one level: { ...state } is a new object, but its nested objects are shared with the old one. A change “in the copy” changes the original, and an undo function restores nothing. The classic workaround JSON.parse( JSON.stringify( obj ) ) makes a deep copy, but it turns dates into strings, drops undefined, Map and Set, and fails on circular references. structuredClone() is the built-in deep copy that handles all of these.

Problem: A plugin’s block-layout builder in the admin keeps an undo history by pushing { ...layout } onto a stack. After a few edits, undo shows the current state, because all history entries share the same nested blocks array. A switch to JSON cloning broke the Date of the last save and a Map of selected items.

Solution: Use structuredClone() for history snapshots and for working copies of nested state, keep the spread operator for shallow, one-level updates, and keep in mind what cannot be cloned: functions, DOM nodes and class instances (which become plain objects).

Shallow copy versus deep copy

const layout = {
    title: 'Home',
    savedAt: new Date(),
    selected: new Map( [ [ 'b1', true ] ] ),
    blocks: [ { id: 'b1', type: 'hero', settings: { align: 'wide' } } ],
};

const shallow = { ...layout };
shallow.blocks[ 0 ].settings.align = 'full';
console.log( layout.blocks[ 0 ].settings.align ); // 'full': the original changed too

const json = JSON.parse( JSON.stringify( layout ) );
console.log( typeof json.savedAt, json.selected ); // 'string', {}: Date and Map are lost

const deep = structuredClone( layout );
deep.blocks[ 0 ].settings.align = 'wide';
console.log( layout.blocks[ 0 ].settings.align ); // still 'full'
console.log( deep.savedAt instanceof Date, deep.selected.get( 'b1' ) ); // true, true

Undo history

const history = [];
let layout = haLoadLayout();

function haCommit( change ) {
    history.push( structuredClone( layout ) ); // snapshot before the change
    if ( history.length > 50 ) history.shift();
    change( layout );
    haRender( layout );
}

function haUndo() {
    if ( history.length ) {
        layout = history.pop();
        haRender( layout );
    }
}

// usage
haCommit( ( l ) => { l.blocks[ 0 ].settings.align = 'full'; } );

Each snapshot is independent, so later changes cannot reach into the history. For large states, cloning on every keystroke is expensive; commit on meaningful steps (blur, drop, button click) instead.

What structuredClone() can and cannot copy

  • Copies: objects, arrays, Date, RegExp, Map, Set, typed arrays, Blob, File, errors, and circular references (the copy is circular too).
  • Throws DataCloneError: functions, DOM nodes, WeakMap, symbols as values.
  • Loses: the prototype of class instances. A cloned new HaBlock() is a plain object without the class methods. Getters are evaluated and copied as values.

That makes it a good fit for data (state from the REST API, settings, layouts) and a bad fit for objects with behavior. For those, write a clone() method in the class.

Not for the block editor’s state

In the block editor, state lives in @wordpress/data stores, which expect immutable updates: a new object for each changed level, created with spread, and unchanged parts kept by reference so that components can skip re-rendering. Deep-cloning a whole store state on every update defeats that. structuredClone() is for copies that should be independent; immutable updates are for state that should share unchanged parts. The copying array methods of ES2023 fit the immutable style: toSorted, toReversed and with.

NOTE: structuredClone() exists in all browsers since 2022 (Chrome 98, Firefox 94, Safari 15.4) and in Node.js 17+. It is the same algorithm the browser uses for postMessage() to Web Workers and for IndexedDB, which is why those have the same rules about what can be transferred.