Skip to content

Instantly share code, notes, and snippets.

@bhashkarsharma
Created September 3, 2023 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhashkarsharma/6058f4574a845e913fde1d9b4f7703f4 to your computer and use it in GitHub Desktop.
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.
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