Skip to content

Instantly share code, notes, and snippets.

@phucdph
Created April 13, 2020 03:24
Show Gist options
  • Select an option

  • Save phucdph/1c78bec2aa926a849bac7e5b8e224dd3 to your computer and use it in GitHub Desktop.

Select an option

Save phucdph/1c78bec2aa926a849bac7e5b8e224dd3 to your computer and use it in GitHub Desktop.
[Hook] useWhyDidUpdate
const useWhyDidYouUpdate = (name: string, props: any) => {
const previousProps = useRef<any>({});
useEffect(() => {
if (previousProps.current) {
const allKeys = Object.keys({
...(previousProps.current || {}),
...props
});
const changesObj = {} as any;
allKeys.forEach(key => {
if (previousProps.current[key] !== props[key]) {
changesObj[key] = {
from: (previousProps.current || {})[key],
to: props[key]
};
}
});
if (Object.keys(changesObj).length) {
console.groupCollapsed(`${name} updated:`);
for (const key in changesObj) {
// eslint-disable-next-line no-useless-concat
console.log(`%c${key}`, "color:red;", "changed", changesObj[key]);
}
console.groupEnd();
}
}
previousProps.current = props;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment