Skip to content

Instantly share code, notes, and snippets.

@casprine
Last active August 2, 2023 13:21
Show Gist options
  • Save casprine/9fa26910ad1cbb9cf5e861dc25ad917e to your computer and use it in GitHub Desktop.
Save casprine/9fa26910ad1cbb9cf5e861dc25ad917e to your computer and use it in GitHub Desktop.
React hook to trace why a component re-render because of prop changes
import { useRef, useEffect } from 'react';
function useTraceUpdate(props: any) {
const prev = useRef(props);
useEffect(() => {
const changedProps = Object.entries(props).reduce((ps, [k, v]) => {
if (prev.current[k] !== v) {
ps[k] = [prev.current[k], v];
}
return ps;
}, {});
if (Object.keys(changedProps).length > 0) {
console.log('Changed props:', changedProps);
}
prev.current = props;
});
}
export default useTraceUpdate;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment