Created
January 2, 2025 17:09
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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