Skip to content

Instantly share code, notes, and snippets.

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