Created
June 15, 2020 18:31
-
-
Save ltwlf/98fb43f6fc57fb61bfab749501ca2cb3 to your computer and use it in GitHub Desktop.
This file contains 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
// 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