Skip to content

Instantly share code, notes, and snippets.

@abm0
Last active June 7, 2019 08:36
Show Gist options
  • Save abm0/50e52612eb6ce3adaaf10b654315da06 to your computer and use it in GitHub Desktop.
Save abm0/50e52612eb6ce3adaaf10b654315da06 to your computer and use it in GitHub Desktop.
Snippet for tracing changed component properties
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`)
);
}
// hook
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;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment