-
-
Save dlebedynskyi/bfb1d74d2e46c4b174fbd4743d046c69 to your computer and use it in GitHub Desktop.
ChangeLog Hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
`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