Skip to content

Instantly share code, notes, and snippets.

@p-jackson
Created April 11, 2019 10:44
Show Gist options
  • Save p-jackson/e66b0ba3ff38ad182b2c0ef3eb171663 to your computer and use it in GitHub Desktop.
Save p-jackson/e66b0ba3ff38ad182b2c0ef3eb171663 to your computer and use it in GitHub Desktop.
What updated in React component
function useTraceUpdate(props) {
const prev = useRef(props);
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;
});
}
componentDidUpdate(prevProps, prevState) {
Object.entries(this.props).forEach(([key, val]) =>
prevProps[key] !== val && console.log(`Prop '${key}' changed`)
);
Object.entries(this.state).forEach(([key, val]) =>
prevState[key] !== val && console.log(`State '${key}' changed`)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment