@atlaskit/renderer
Version:
Renderer component
39 lines (37 loc) • 1.62 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useMemoFromPropsDerivative = useMemoFromPropsDerivative;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = require("react");
/* eslint-disable jsdoc/require-jsdoc */
function useMemoFromPropsDerivative(factory, propsDerivator, props) {
// cache the last set of props
var prev = (0, _react.useRef)(props);
var prevFactory = (0, _react.useRef)(null);
return (0, _react.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 = (0, _slicedToArray2.default)(_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]);
}