Skip to content

Instantly share code, notes, and snippets.

@bozdoz
Last active July 5, 2023 20:15
Show Gist options
  • Save bozdoz/674df648b9e1b16a92cf2c00a7477d7a to your computer and use it in GitHub Desktop.
Save bozdoz/674df648b9e1b16a92cf2c00a7477d7a to your computer and use it in GitHub Desktop.
useWhyDidYouUpdate
import { useRef, useEffect } from 'react';
type IProps = Record<string, unknown>;
const useWhyDidYouUpdate = (componentName: any, props: any) => {
const oldPropsRef = useRef<IProps>({});
useEffect(() => {
if (oldPropsRef.current) {
// iterate through all the key of the old and new props
const keys = Object.keys({ ...oldPropsRef.current, ...props });
// change the information object
const changeMessageObj: IProps = {};
keys.forEach((key) => {
// compare whether the new and old props are changed, changed and recorded to changeMessageObj
if (!Object.is(oldPropsRef.current[key], props[key])) {
changeMessageObj[key] = {
from: oldPropsRef?.current[key],
to: props[key]
};
}
});
// whether there is change information, existence and printing
if (Object.keys(changeMessageObj).length) {
// eslint-disable-next-line no-console
console.log(componentName, changeMessageObj);
}
// Update ref
oldPropsRef.current = props;
}
});
};
export default useWhyDidYouUpdate;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment