Deep Clone Utility
Safely create a deep copy of objects and arrays without affecting the original data.
Copying nested objects or arrays by reference can lead to unexpected mutations. A deep clone utility ensures that updates to the copy won’t ripple back to the original. While JSON.parse(JSON.stringify(obj))
works for simple data, it fails on Date objects, functions, or undefined values. Here’s a more robust approach using the structured clone algorithm if available, with a fallback to JSON for environments without structuredClone
.
export function deepClone(value) {
if (typeof globalThis.structuredClone === "function") {
return globalThis.structuredClone(value);
}
return JSON.parse(JSON.stringify(value));
}
Use this helper when you need to duplicate complex state in React reducers, copy configuration objects before modifying them, or snapshot data structures for debugging. It returns a pristine copy, leaving your original objects untouched.