Last active
July 13, 2022 03:35
-
-
Save muhsalaa/af66ebf3d220f50218609b9e4abe2101 to your computer and use it in GitHub Desktop.
Trace prop change in react component
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>; | |
} | |
// 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