-
Notifications
You must be signed in to change notification settings - Fork 0
useDeepClone
A React hook that safely and deeply clones an object or array, ensuring you get a completely new memory reference. However, it smartly skips the expensive cloning process entirely if the input object hasn't changed since the last render.
Generating a safe clone of a prop to mutate it locally without polluting the parent component's state.
import { useState } from "react";
import { useDeepClone } from "react-hook-lab";
function ConfigEditor({ defaultSettings }: { defaultSettings: any }) {
// Safely clone the deeply nested settings object once.
// Because useDeepClone memoizes based on reference equality, it won't
// needlessly re-clone on every re-render of ConfigEditor.
const safeSettings = useDeepClone(defaultSettings);
const [localSettings, setLocalSettings] = useState(safeSettings);
return (
<div>
<input
value={localSettings.theme.color}
onChange={e => setLocalSettings(prev => {
prev.theme.color = e.target.value;
return { ...prev };
})}
/>
</div>
);
}-
value- Type:
T - Description: The deeply nested object, array, or data structure you wish to clone.
- Type:
Returns T, a completely new memory reference containing deeply cloned data.
useDeepClone combines React's useMemo and useRef with our highly optimized deepClone utility.
On the first render, it performs a full structural deep clone of the input value.
On subsequent renders, it strictly compares the memory reference (===) of the input value. If the reference hasn't changed, it entirely skips the deepClone logic and immediately returns the cached clone from the previous render. This saves significant CPU cycles compared to manually calling deepClone directly inside a component body.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM