Skip to content

Instantly share code, notes, and snippets.

@dlebedynskyi
Forked from joshwcomeau/use-change-log.hook.js
Created November 6, 2018 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dlebedynskyi/bfb1d74d2e46c4b174fbd4743d046c69 to your computer and use it in GitHub Desktop.
Save dlebedynskyi/bfb1d74d2e46c4b174fbd4743d046c69 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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment