JAVASCRIPT

React useWhyDidYouUpdate Hook for Debugging Renders

Create a `useWhyDidYouUpdate` hook to log component re-renders and identify which prop or state changes are causing them, aiding performance debugging.

import { useRef, useEffect } from 'react';

function useWhyDidYouUpdate(name, props) {
  const previousProps = useRef();

  useEffect(() => {
    if (previousProps.current) {
      const allKeys = Object.keys({ ...previousProps.current, ...props });
      const changedProps = {};
      allKeys.forEach((key) => {
        if (previousProps.current[key] !== props[key]) {
          changedProps[key] = {
            from: previousProps.current[key],
            to: props[key],
          };
        }
      });

      if (Object.keys(changedProps).length) {
        console.log('[why-did-you-update]', name, changedProps);
      }
    }
    previousProps.current = props;
  });
}
How it works: The `useWhyDidYouUpdate` hook helps debug unnecessary component re-renders by logging which props have changed between renders. It stores the previous props using `useRef` and compares them to the current props in a `useEffect`. If differences are found, it logs them to the console. This is an invaluable tool for identifying performance bottlenecks caused by unintentional prop changes or state updates in parent components.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs