Skip to content

Instantly share code, notes, and snippets.

@muhsalaa
Last active July 13, 2022 03:35
Show Gist options
  • Save muhsalaa/af66ebf3d220f50218609b9e4abe2101 to your computer and use it in GitHub Desktop.
Save muhsalaa/af66ebf3d220f50218609b9e4abe2101 to your computer and use it in GitHub Desktop.
Trace prop change in react component
function useTraceUpdate(props) {
const prev = React.useRef(props);
React.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;
});
}
// Usage
function MyComponent(props) {
useTraceUpdate(props);
return <div>{props.children}</div>;
}
// https://stackoverflow.com/questions/41004631/trace-why-a-react-component-is-re-rendering
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment