Skip to content

Instantly share code, notes, and snippets.

@ltwlf
Created June 15, 2020 18:31
Show Gist options
  • Save ltwlf/98fb43f6fc57fb61bfab749501ca2cb3 to your computer and use it in GitHub Desktop.
Save ltwlf/98fb43f6fc57fb61bfab749501ca2cb3 to your computer and use it in GitHub Desktop.
// source https://github.com/apollographql/apollo-client/blob/master/src/react/hooks/utils/useDeepMemo.ts
import { useRef } from 'react';
import { equal } from '@wry/equality';
/**
* Memoize a result using deep equality. This hook has two advantages over
* React.useMemo: it uses deep equality to compare memo keys, and it guarantees
* that the memo function will only be called if the keys are unequal.
* React.useMemo cannot be relied on to do this, since it is only a performance
* optimization (see https://reactjs.org/docs/hooks-reference.html#usememo).
*/
export function useDeepMemo<TKey, TValue>(
memoFn: () => TValue,
key: TKey
): TValue {
const ref = useRef<{ key: TKey; value: TValue }>();
if (!ref.current || !equal(key, ref.current.key)) {
ref.current = { key, value: memoFn() };
}
return ref.current.value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment