How to Create a useWhyDidYouRender Hook in React
To create a custom useWhyDidYouRender
hook in React to debug your functional components, you can use a useEffect
hook combined with a useRef
:
useWhyDidYouRender = props => {
const ref = useRef(props);
useEffect(() => {
const changedProps = Object.entries(props).reduce((prop, [key, value]) => {
if (ref.current[key] !== value) {
prop[key] = [ref.current[key], value];
}
return prop;
}, {});
if (Object.keys(changedProps).length > 0) {
console.log(`rerender cause: ${changedProps}`);
}
ref.current = props;
});
}
This custom hook collects all of the changed props from your component by populating the changedProps
object. If one of the current props has a different value compared to its previous value, it will be added to the object. And in case the object is not empty, then those changed props will be logged to the console.
This makes it easy to spot unnecessary re-renders and improve the performance of your React components, by checking which prop causes a re-render and whether you should memo your component.
If you are interested in reading more about React hooks, see more examples for custom hooks or just learn about the basics, make sure to check out the article below.
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: