How to Create a useWhyDidYouRender Hook in React

How to Create a useWhyDidYouRender Hook in React

Ferenc Almasi β€’ 2022 January 11 β€’ Read time 2 min read
  • twitter
  • facebook
React

To create a custom useWhyDidYouRender hook in React to debug your functional components, you can use a useEffect hook combined with a useRef:

Copied to clipboard! Playground
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;
    });
}
useWhyDidYouRender.js

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.

How to Create a useWhyDidYouRender Hook in React
  If you would like to see more Webtips, follow @flowforfrank

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.

All You Need to Know About React Hooks
  • twitter
  • facebook
React
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

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:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.