Skip to content

Instantly share code, notes, and snippets.

@l-portet
Created September 12, 2023 15:39
Show Gist options
  • Save l-portet/272de2ce32c558756dfad07ff6e53d67 to your computer and use it in GitHub Desktop.
Save l-portet/272de2ce32c558756dfad07ff6e53d67 to your computer and use it in GitHub Desktop.
Trace what triggers a React component re-render
// extracted from https://github.com/damiangreen/use-trace-update
import { useEffect, useRef } from 'react';
export default function useTraceUpdate(props) {
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;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment