Skip to main content

deepClone()

deepClone<T>(value): T

Creates a deep clone of a value, recursively cloning nested structures.

Handles primitives, arrays, Date, Map, Set, RegExp, Error, and plain objects. Preserves prototypes and symbol keys. Handles circular references. Functions are copied by reference (not cloned).

For TypedArrays, ArrayBuffer, Buffer, Blob, File, use deepCloneFull instead.


Type Parametersโ€‹

T: Tโ€‹

The type of the destination object.


Parametersโ€‹

value: Tโ€‹

The value to deep clone.


Returns: Tโ€‹

A deep clone of the value.


Sinceโ€‹

2.0.0


Performanceโ€‹

O(n) time & space where n is total number of properties/elements.


Also known asโ€‹

clone (Remeda, Ramda) ยท cloneDeep (Lodash, es-toolkit, Radashi) ยท โŒ (Effect, Modern Dash, Antfu)


Examplesโ€‹

const original = { a: 1, b: { c: 2 }, d: [3, 4] };
const cloned = deepClone(original);
cloned.b.c = 99;
original.b.c; // => 2 (unchanged)
const circular: `Record<string, unknown>` = { a: 1 };
circular.self = circular;
const cloned = deepClone(circular);
cloned.self === cloned; // => true

How it works?โ€‹

Creates a deep copy of a value, recursively cloning all nested structures.

Independenceโ€‹

Circular Reference Handlingโ€‹


Use Casesโ€‹

Duplicate simple state ๐Ÿ“Œโ€‹

Create a deep copy of an object to avoid mutation bugs. Essential for Redux-style state updates or immutable patterns.

const newState = deepClone(currentState);
newState.user.isActive = true; // Safe mutation

Snapshot state historyโ€‹

Store copies of state at specific points in time for undo/redo functionality.

const history = [];
function pushState(state) {
history.push(deepClone(state));
}

Break referencesโ€‹

Ensure that nested objects are fully decoupled from the original. Useful when passing data to components that might mutate it.

const original = { config: { retries: 3 } };
const copy = deepClone(original);
copy.config.retries = 5;
console.log(original.config.retries); // 3

Clone form state for reset and dirty-checkingโ€‹

Store the initial form state to enable "Reset" and detect unsaved changes. Universal pattern for form-heavy applications with save/discard workflows.

const initialValues = deepClone(formData);

// User edits the form...
formData.name = "Updated Name";
formData.address.city = "New City";

// Dirty check: compare current state with original
const hasChanges = JSON.stringify(formData) !== JSON.stringify(initialValues);
// => true

// Reset: restore original values
function resetForm() {
Object.assign(formData, deepClone(initialValues));
}