Skip to content

Instantly share code, notes, and snippets.

@theonlydaleking
Created May 12, 2022 04:25
Show Gist options
  • Save theonlydaleking/81f0374feedba3931412dc188e7eb47b to your computer and use it in GitHub Desktop.
Save theonlydaleking/81f0374feedba3931412dc188e7eb47b to your computer and use it in GitHub Desktop.
What caused a re-render?
// Tracks what prop is changing to trigger re-render
// shout out to this legend
// https://stackoverflow.com/a/51082563/5157083
// usage useTraceUpdate(props)
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
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment