Skip to content

Instantly share code, notes, and snippets.

@tincho
Last active September 19, 2019 19:55
Embed
What would you like to do?
memoize by props shortcut
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