Skip to content

Instantly share code, notes, and snippets.

@Borovensky
Created March 13, 2024 16:06
Show Gist options
  • Save Borovensky/8fddba56c9adf77007652140a7cd7225 to your computer and use it in GitHub Desktop.
Save Borovensky/8fddba56c9adf77007652140a7cd7225 to your computer and use it in GitHub Desktop.
useWhyDidYouUpdate.ts
function useWhyDidYouUpdate(name: string, props: any) {
// Get a mutable ref object where we can store props ...
// ... for comparison next time this hook runs.
const previousProps = React.useRef<any>();
React.useEffect(() => {
if (previousProps.current) {
// Get all keys from previous and current props
const allKeys = Object.keys({ ...previousProps.current, ...props });
// Use this object to keep track of changed props
const changesObj = {} as any;
// Iterate through keys
allKeys.forEach((key) => {
// If previous is different from current
if (previousProps.current[key] !== props[key]) {
// Add to changesObj
changesObj[key] = {
from: previousProps.current[key],
to: props[key],
};
}
});
// If changesObj not empty then output to console
if (Object.keys(changesObj).length) {
console.log('[why-did-you-update]', name, changesObj);
}
}
// Finally update previousProps with current props for next hook call
previousProps.current = props;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment