Skip to content

Instantly share code, notes, and snippets.

@ivanbtrujillo
Last active July 6, 2020 18:46
Show Gist options
  • Save ivanbtrujillo/3e2944a19432106099fbbc6df766c8e4 to your computer and use it in GitHub Desktop.
Save ivanbtrujillo/3e2944a19432106099fbbc6df766c8e4 to your computer and use it in GitHub Desktop.
react-usewhydidyouupdate.tsx
import { useEffect, useRef } from 'react';
type GenericProps = { [key: string]: any };
export const useWhyDidYouUpdate = (componentName: string, props: GenericProps) => {
console.warn(`Remove useWhyDidYouUpdate from component ${componentName} before commit your changes`);
/*
* Get a mutable ref object where we can store props
* for comparison next time this hook runs.
*/
const previousProps: React.MutableRefObject<GenericProps> = useRef({ current: {} });
useEffect(() => {
if (previousProps.current) {
// Get all keys from previous and current props
const allKeys = Object.keys({ ...previousProps.current, ...props });
// Use this changes object to keep track of changed props
const changes = Object.values(allKeys).reduce((acc, key) => {
if (previousProps.current![key] !== props[key]) {
return {
...acc,
[key]: {
from: previousProps.current![key],
to: props[key],
},
};
}
return acc;
}, {});
// If changes object is not empty, then show the changes
if (Object.keys(changes).length) {
console.info('[why-did-you-update?:]', componentName, changes);
}
}
// Finally update previousProps with current props for next hook call
previousProps.current = props;
});
};
/* HOW TO USE */
useWhyDidYouUpdate('Component name', props)
/* DEEP COMPARISON */
// For deep comparison, replace the if in line 18 by lodash isEqual (or other algorith you prefer):
if (!isEqual(previousProps.current![key], props[key]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment