Skip to content

deepClone

Saurav-TB-Pandey edited this page Aug 10, 2026 · 2 revisions

deepClone

An ultra-fast, security-hardened utility function for deeply cloning JavaScript data structures. It prevents Prototype Pollution attacks, securely manages circular dependencies, natively clones Map, Set, Date, and TypedArrays, and intelligently skips cloning immutable objects to massively boost performance.

Usage Examples

Basic

Creating a completely independent copy of a deeply nested object so you can mutate it safely.

import { deepClone } from "react-hook-lab";

const original = {
  settings: { theme: "dark" },
  tags: ["react", "hooks"]
};

const clone = deepClone(original);

// Mutating the clone does NOT affect the original
clone.settings.theme = "light";
clone.tags.push("performance");

console.log(original.settings.theme); // "dark"
console.log(original.tags.length); // 2

Common

Safely cloning advanced data types without losing data integrity.

import { deepClone } from "react-hook-lab";

const complexData = {
  timestamp: new Date(),
  pattern: /react/gi,
  cache: new Map([['user1', { id: 1 }]])
};

const safeCopy = deepClone(complexData);

console.log(safeCopy.timestamp instanceof Date); // true
console.log(safeCopy.cache instanceof Map); // true

API Reference

Parameters

  • value (T): The value, object, array, or data structure you wish to recursively clone.

Return Type

Returns T, a structurally identical but completely unlinked memory reference.

Core Working

deepClone is engineered for extreme performance and strict security:

  1. Primitive Fast-path: If the value is null or not an object (e.g. string, number), it returns the value immediately without processing.
  2. Frozen Optimization: If an object is strictly immutable (Object.isFrozen), it completely skips cloning and returns the original shared reference to save massive amounts of CPU cycles.
  3. DOM Shielding: Attempting to deep-clone a raw DOM Element causes catastrophic memory spikes in JavaScript. deepClone detects DOM elements and refuses to clone them, returning the original reference.
  4. Native Fast-paths: TypedArrays (like Uint8Array) are natively cloned using their .slice() method in C++ space, rather than iterating byte-by-byte in JavaScript.
  5. Security: When cloning plain objects, it strictly skips __proto__ and constructor keys to eliminate Prototype Pollution vulnerabilities. It also reconstructs the prototype chain using Object.create(Object.getPrototypeOf()) so custom class instances don't lose their methods.

Clone this wiki locally