Back to Code Bytes
2 min read
deepClone()

Description

deepClone leverages the browser’s built-in structuredClone function to perform a full deep copy of the provided value, preserving nested objects, arrays, Maps, Sets, and more.

Code Byte

export function deepClone<T>(obj: T): T {
  return structuredClone(obj);
}

Resources:

Use cases:

  • State Management: Clone complex state trees in React or other frameworks to enforce immutability.
  • Undo/Redo: Capture snapshots of the application state for rollback functionality.
  • Data Sanitization: Work on a copy of input data without mutating the original.
  • Offline Caching: Deeply clone fetched data before storing to IndexedDB or other caches.

Example Usage:

import { deepClone } from './deep-clone.util';

interface User {
  name: string;
  preferences: {
    theme: string;
    notifications: boolean;
  };
}

const original: User = {
  name: 'Alice',
  preferences: {
    theme: 'dark',
    notifications: true,
  },
};

// Create a deep copy
const copy = deepClone(original);

// Mutate the copy without affecting the original
copy.preferences.theme = 'light';

console.log(original.preferences.theme); // "dark"
console.log(copy.preferences.theme);     // "light"