Created
October 31, 2018 06:04
-
-
Save Volune/0c9014dbbae2e1bfb647caf8bb69dac1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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