Skip to content

Instantly share code, notes, and snippets.

@Volune
Created October 31, 2018 06:04
Show Gist options
  • Save Volune/0c9014dbbae2e1bfb647caf8bb69dac1 to your computer and use it in GitHub Desktop.
Save Volune/0c9014dbbae2e1bfb647caf8bb69dac1 to your computer and use it in GitHub Desktop.
import { useRef } from 'react';
const getComponentName = WrappedComponent => (
WrappedComponent.displayName || WrappedComponent.name || 'Unknown'
);
const compareProps = (obj1, obj2) => {
let keys1 = Object.keys(obj1);
const sameValues = keys1.every(
key => obj2.hasOwnProperty(key) && obj2[key] === obj1[key],
);
return sameValues && keys1.length === Object.keys(obj2).length;
};
const memoPureComponent = WrappedComponent => {
const Wrapper = (ownProps) => {
const ref = useRef(null);
if (!ref.current) {
ref.current = {
rendered: WrappedComponent(ownProps),
props: ownProps,
};
} else if (!compareProps(ref.current.props, ownProps)) {
ref.current.rendered = WrappedComponent(ownProps);
ref.current.props = ownProps;
}
return ref.current.rendered;
};
Wrapper.displayName = `memo(${getComponentName(WrappedComponent)})`;
return Wrapper;
};
export default memoPureComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment