memoize by props shortcut
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
const shallowCompare = (obj1, obj2) => | |
typeof obj1 === 'object' && typeof obj2 === 'object' | |
? Object.keys(obj1).length === Object.keys(obj2).length && | |
Object.keys(obj1).every( | |
key => obj2.hasOwnProperty(key) && obj1[key] === obj2[key] | |
) | |
: obj1 === obj2 | |
const memoizeByProps = (...props) => Component => | |
React.memo(Component, (prevProps, nextProps) => | |
props.every(prop => shallowCompare(prevProps[prop], nextProps[prop])) | |
) | |
// usage: MemoizedComponent = memoizeByProps('propName' /*, 'otherProp', 'etc' */)(Component) | |
export default memoizeByProps |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment