UNPKG

@atlaskit/renderer

Version:
25 lines 1.13 kB
/* eslint-disable jsdoc/require-jsdoc */ import { useMemo, useRef } from 'react'; export function useMemoFromPropsDerivative(factory, propsDerivator, props) { // cache the last set of props const prev = useRef(props); const prevFactory = useRef(null); return useMemo(() => { // check if the serializer is already created let shouldCreate = !prevFactory.current; // check each prop to see if value has changed and also check if the number of props has changed if (prev.current !== props) { const propsEntries = Object.entries(props); shouldCreate = propsEntries.length !== Object.keys(prev.current).length || propsEntries.some(([key, prop]) => prev.current[key] !== prop); } prev.current = props; // If first time or any prop value has changed, create a new serializer if (shouldCreate) { prevFactory.current = factory(propsDerivator(props)); } return prevFactory.current; }, // To keep deps consistent, here disable the exhaustive-deps rule to drop factory from the deps array // eslint-disable-next-line react-hooks/exhaustive-deps [propsDerivator, props]); }