Skip to content

Instantly share code, notes, and snippets.

@pffigueiredo
Last active November 3, 2023 11:24
Show Gist options
  • Save pffigueiredo/40ccfc6ee796bdc592e1b56cb029dd1a to your computer and use it in GitHub Desktop.
Save pffigueiredo/40ccfc6ee796bdc592e1b56cb029dd1a to your computer and use it in GitHub Desktop.
React hook to debug what props are triggering a re-render
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>;
}
// --- callback version
function useTraceUpdateCallback(initialProps) {
const prev = React.useRef(initialProps);
const callback = React.useCallback((props) => {
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;
}, []);
return callback;
}
// Usage
function MyComponent(props) {
const traceCallback = useTraceUpdateCallback(props);
traceCallback(props);
return <div>{props.children}</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment