Skip to content

Instantly share code, notes, and snippets.

@iamakulov
Created June 18, 2023 22:49
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 iamakulov/786f3575df369eede240440bb55f8398 to your computer and use it in GitHub Desktop.
Save iamakulov/786f3575df369eede240440bb55f8398 to your computer and use it in GitHub Desktop.
// A copy-pasteable useWhyDidYouUpdate hook, adopted from the old & good usehooks.com (http://web.archive.org/web/20230203011511/https://usehooks.com/useWhyDidYouUpdate/).
//
// This hook will log whenever a component rerenders – and will print the props (or any other values
// you passed into it) that have changed between the rerenders.
//
// Usage:
//
// function MyComponent(props) {
// useWhyDidYouUpdate('MyComponent', props)
//
// ...
// }
//
// Works with hooks and any other values as well:
//
// function MyComponent(props) {
// const user = useSelector(userSelector)
// const article = useSelector(articleSelector)
//
// useWhyDidYouUpdate('MyComponent hooks', { user, article })
//
// ...
// }
function useWhyDidYouUpdate(name, props) {
// Get a mutable ref object where we can store props ...
// ... for comparison next time this hook runs.
const previousProps = useRef();
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 = {};
// 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