Skip to content

Instantly share code, notes, and snippets.

@parkerziegler
Created September 19, 2019 10:41
Show Gist options
  • Save parkerziegler/e212f48f4d00e99e256661544033dff2 to your computer and use it in GitHub Desktop.
Save parkerziegler/e212f48f4d00e99e256661544033dff2 to your computer and use it in GitHub Desktop.
A simple React hook to run a shallow comparison over all key-value pairs in an object against their previous values. Useful for determining which of your props are triggering unexpected re-renders.
import React from 'react';
/* eslint-disable no-console */
export const useTraceUpdate = <P>(props: P) => {
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;
});
};
/* eslint-enable no-console */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment