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));
}