Last active
February 25, 2020 21:05
-
-
Save trentmwillis/0a8664e315942aee8c693563934a6e35 to your computer and use it in GitHub Desktop.
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 { useEffect, useRef } from 'react'; | |
/** | |
* A small utility hook to help figure out what is changing and causing | |
* re-renders. Add it to the component you're investigating and pass in a object | |
* of the values that you think might be changing. | |
* | |
* Ex: useWhatChanged({ someProp, someOtherProp }); | |
*/ | |
export function useWhatChanged(props) { | |
const previousProps = useRef(props); | |
useEffect(() => { | |
const changedProps = Object.entries(props).reduce((result, [key, value]) => { | |
const previousValue = previousProps.current[key]; | |
return previousValue !== value ? | |
{ ...result, [key]: [previousValue, value] } : | |
result; | |
}, {}); | |
if (Object.keys(changedProps).length > 0) { | |
console.info('The following props changed:', changedProps); | |
} else { | |
console.info('No props changed.'); | |
} | |
previousProps.current = props; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment