Skip to content

Instantly share code, notes, and snippets.

@codemile
Created January 2, 2025 17:09
Show Gist options
  • Save codemile/7e1b1ce15078eb662f96721cd0afa703 to your computer and use it in GitHub Desktop.
Save codemile/7e1b1ce15078eb662f96721cd0afa703 to your computer and use it in GitHub Desktop.
Custom React hook for deep memoization of values with a configurable equality function using useRef.
import { useRef } from 'react';
import isEqual from 'lodash.isequal';
export function useDeepMemo<TValue>(
value: TValue,
isEqualFn: (a: TValue, b: TValue) => boolean = isEqual
): TValue {
const ref = useRef<TValue>(value);
// Update ref if the value has changed
if (!isEqualFn(ref.current, value)) {
ref.current = value;
}
// Return the memoized value
return ref.current;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment