@zohodesk/components
Version:
In this Package, we Provide Some Basic Components to Build Web App
38 lines (35 loc) • 1.22 kB
JavaScript
/** ** Libraries *** */
import { useContext, useRef } from 'react';
import PropTypes from 'prop-types';
import shallowEqual from "./shallowEqual"; // Please use this component with children as inline function for force this components rerender when parent rerender regardless of reason
// Because below componends only rerender when children or calculation are changed, unless no changes will update below
// this component logic based on return same children reference to stop rerender.
// Think before change logic
// eslint-disable-next-line import/prefer-default-export
export function ContextOptimizer(props) {
const {
Context,
children: renderF,
calculation
} = props;
const contextData = useContext(Context);
const data = calculation(contextData);
const {
current: local
} = useRef({
children: null,
data: null,
renderF: null
});
if (!shallowEqual(data, local.data) || local.renderF !== renderF) {
local.children = renderF(data);
local.data = data;
local.renderF = renderF;
}
return local.children;
}
ContextOptimizer.propTypes = {
calculation: PropTypes.func.isRequired,
children: PropTypes.func.isRequired,
Context: PropTypes.any.isRequired
};