Created
September 19, 2019 10:41
-
-
Save parkerziegler/e212f48f4d00e99e256661544033dff2 to your computer and use it in GitHub Desktop.
A simple React hook to run a shallow comparison over all key-value pairs in an object against their previous values. Useful for determining which of your props are triggering unexpected re-renders.
This file contains hidden or 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 React from 'react'; | |
/* eslint-disable no-console */ | |
export const useTraceUpdate = <P>(props: P) => { | |
const prev = React.useRef(props); | |
React.useEffect(() => { | |
const changedProps = Object.entries(props).reduce((ps, [k, v]) => { | |
if (prev.current[k] !== v) { | |
ps[k] = [prev.current[k], v]; | |
} | |
return ps; | |
}, {}); | |
if (Object.keys(changedProps).length > 0) { | |
console.log('Changed props:', changedProps); | |
} | |
prev.current = props; | |
}); | |
}; | |
/* eslint-enable no-console */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment