-
Notifications
You must be signed in to change notification settings - Fork 0
deepClone
Saurav-TB-Pandey edited this page Aug 10, 2026
·
2 revisions
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.
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); // 2Safely 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-
value(T): The value, object, array, or data structure you wish to recursively clone.
Returns T, a structurally identical but completely unlinked memory reference.
deepClone is engineered for extreme performance and strict security:
-
Primitive Fast-path: If the value is
nullor not an object (e.g.string,number), it returns the value immediately without processing. -
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. -
DOM Shielding: Attempting to deep-clone a raw DOM
Elementcauses catastrophic memory spikes in JavaScript.deepClonedetects DOM elements and refuses to clone them, returning the original reference. -
Native Fast-paths: TypedArrays (like
Uint8Array) are natively cloned using their.slice()method in C++ space, rather than iterating byte-by-byte in JavaScript. -
Security: When cloning plain objects, it strictly skips
__proto__andconstructorkeys to eliminate Prototype Pollution vulnerabilities. It also reconstructs the prototype chain usingObject.create(Object.getPrototypeOf())so custom class instances don't lose their methods.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM