Skip to content

Instantly share code, notes, and snippets.

@bhashkarsharma
Created January 6, 2024 11:43
Show Gist options
  • Save bhashkarsharma/48543416c8ca83eaee21f8b2dd6a0fd7 to your computer and use it in GitHub Desktop.
Save bhashkarsharma/48543416c8ca83eaee21f8b2dd6a0fd7 to your computer and use it in GitHub Desktop.
Debug React component rendering with this JS hook (includes render count logging)
import { useEffect, useRef } from 'react';
const PREFIX = '[useComponentDebug]';
export default function useComponentDebug(componentName, props) {
const prevProps = useRef({});
console.count(`${PREFIX} ${componentName} render`);
useEffect(() => {
console.count(`${PREFIX} ${componentName} mount`);
return () => console.count(`xxx ${componentName} unmount`);
}, [componentName]);
useEffect(() => {
if (prevProps.current) {
const allKeys = Object.keys({ ...prevProps.current, ...props });
const changedProps = {};
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(
PREFIX,
componentName,
// changedProps
JSON.stringify(changedProps, null, 2)
);
}
}
prevProps.current = props;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment