Created
January 24, 2022 16:19
-
-
Save freddi301/24fa95a80744c19237bc2e6adb68db7f to your computer and use it in GitHub Desktop.
useWhyDidYouUpdate react hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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