← Back to all snippets
JAVASCRIPT

Debugging React Re-renders with useWhyDidYouRender Hook

Discover how to create `useWhyDidYouRender`, a powerful debugging React hook that logs prop and state changes causing unnecessary component re-renders.

import { useRef, useEffect } from 'react';

// This hook is for development purposes only.
// It should not be used in production.
function useWhyDidYouRender(name, props) {
  const previousProps = useRef({});

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

      if (Object.keys(changes).length > 0) {
        console.log('[why-did-you-render]', name, changes);
      }
    }

    previousProps.current = props;
  }); // No dependency array, runs on every render

}

// Example Usage:
/*
function MyComponent(props) {
  useWhyDidYouRender('MyComponent', props);
  // ... component logic ...
  return <div>{props.value}</div>;
}
// Make sure to pass a name to the hook for clear logging
*/
How it works: The `useWhyDidYouRender` hook is a debugging utility. It takes a component `name` and its `props` as arguments. It uses `useRef` to store the `props` from the *previous* render. In a `useEffect` that runs on every render, it compares the current `props` with the `previousProps`. If any prop has changed, it logs the component name and the specific changes (what prop changed, from what value, to what value) to the console, helping developers identify and optimize unnecessary re-renders.

Need help integrating this into your project?

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

Hire DigitalCodeLabs