Last active
September 19, 2019 19:55
-
-
Save tincho/772d607a34b1a597f697f44c0deca2e2 to your computer and use it in GitHub Desktop.
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