Last active
November 3, 2023 11:24
-
-
Save pffigueiredo/40ccfc6ee796bdc592e1b56cb029dd1a to your computer and use it in GitHub Desktop.
React hook to debug what props are triggering a re-render
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
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