@atlaskit/renderer
Version:
Renderer component
31 lines • 1.32 kB
JavaScript
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
/* eslint-disable jsdoc/require-jsdoc */
import { useMemo, useRef } from 'react';
export function useMemoFromPropsDerivative(factory, propsDerivator, props) {
// cache the last set of props
var prev = useRef(props);
var prevFactory = useRef(null);
return useMemo(function () {
// check if the serializer is already created
var 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) {
var propsEntries = Object.entries(props);
shouldCreate = propsEntries.length !== Object.keys(prev.current).length || propsEntries.some(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
prop = _ref2[1];
return 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]);
}