Skip to content

Instantly share code, notes, and snippets.

@joshwcomeau
Last active December 12, 2021 04:29
Show Gist options
  • Save joshwcomeau/09b0fb62114fa0a2c59b84e16053c78b to your computer and use it in GitHub Desktop.
Save joshwcomeau/09b0fb62114fa0a2c59b84e16053c78b to your computer and use it in GitHub Desktop.
ChangeLog Hook
/**
`useChangeLog` - dev-mode helper hook to let you
know why a memoized component re-rendered!
Usage example:
const YourComponent = React.memo((props) => {
// Just drop this fella into your memo component's body.
useChangeLog(props);
return <div>Hello World</div>
});
*/
import { useEffect, useRef } from 'react';
const useChangeLog = props => {
if (process.env.NODE_ENV === 'production') {
return;
}
const staleProps = useRef(props);
useEffect(() => {
const changedProps = Object.keys(props)
.map(key => {
const hasChanged = props[key] !== staleProps.current[key];
if (!hasChanged) {
return null;
}
return {
prop: key,
from: getPrintableValue(staleProps.current[key]),
to: getPrintableValue(props[key]),
};
})
.filter(prop => !!prop);
if (changedProps.length) {
console.info('▬▬▬ UPDATE TRIGGERED ▬▬▬');
console.table(changedProps);
console.info('\n\n\n');
}
staleProps.current = props;
});
};
const getPrintableValue = val => {
switch (typeof val) {
case 'function':
return '[function]';
case 'number':
case 'string':
default:
return val;
}
};
export default useChangeLog;
@joshwcomeau
Copy link
Author

(getPrintableValue could be made a lot better, to handle objects and arrays. This code is yours to improve!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment