Created
January 6, 2024 11:43
-
-
Save bhashkarsharma/48543416c8ca83eaee21f8b2dd6a0fd7 to your computer and use it in GitHub Desktop.
Debug React component rendering with this JS hook (includes render count logging)
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'; | |
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