Skip to content

Instantly share code, notes, and snippets.

@trentmwillis
Last active February 25, 2020 21:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trentmwillis/0a8664e315942aee8c693563934a6e35 to your computer and use it in GitHub Desktop.
Save trentmwillis/0a8664e315942aee8c693563934a6e35 to your computer and use it in GitHub Desktop.
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