Skip to content

Instantly share code, notes, and snippets.

@freddi301
Created January 24, 2022 16:19
Show Gist options
  • Save freddi301/24fa95a80744c19237bc2e6adb68db7f to your computer and use it in GitHub Desktop.
Save freddi301/24fa95a80744c19237bc2e6adb68db7f to your computer and use it in GitHub Desktop.
useWhyDidYouUpdate react hook
import React from "react"
export function useWhyDidYouUpdate<Props extends Record<string, any>>(label: string, props: Props) {
const previousProps = React.useRef<Props>();
React.useEffect(() => {
if (previousProps.current) {
const allKeys = Object.keys({ ...previousProps.current, ...props }) as Array<keyof Props>;
const changesObj: {[K in keyof Props]?: {from: Props[K], to: Props[K]}} = {};
for (const key of allKeys) {
if (previousProps.current[key] !== props[key]) {
changesObj[key] = {
from: previousProps.current[key],
to: props[key],
};
}
}
if (Object.keys(changesObj).length) {
console.log("[why-did-you-update]", label, changesObj);
}
}
previousProps.current = props;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment