Created
September 3, 2023 06:25
-
-
Save bhashkarsharma/6058f4574a845e913fde1d9b4f7703f4 to your computer and use it in GitHub Desktop.
React hook to track changes across render cycles. One of the most useful utilities for debugging perf or rendering weirdness.
This file contains 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 { useEffect, useRef } from 'react'; | |
export type Props = Record<string, any>; | |
export default function useWhyDidComponentUpdate(componentName: string, props: Props) { | |
const prevProps = useRef<Props>({}); | |
useEffect(() => { | |
if (prevProps.current) { | |
const allKeys = Object.keys({ ...prevProps.current, ...props }); | |
const changedProps: Props = {}; | |
allKeys.forEach((key) => { | |
if (!Object.is(prevProps.current[key], props[key])) { | |
changedProps[key] = { | |
from: prevProps.current[key], | |
to: props[key], | |
}; | |
} | |
}); | |
if (Object.keys(changedProps).length) { | |
console.log('[whyDidComponentUpdate]', componentName, changedProps); | |
} | |
} | |
prevProps.current = props; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment