JAVASCRIPT
React `useWhyDidYouUpdate` for Debugging Re-renders
Identify and debug unnecessary React component re-renders by logging changes in props or state using the `useWhyDidYouUpdate` hook, helping optimize application performance.
import { useRef, useEffect } from 'react';
function useWhyDidYouUpdate(name, props) {
const previousProps = useRef({});
useEffect(() => {
if (previousProps.current) {
const allKeys = Object.keys({ ...previousProps.current, ...props });
const changesObj = {};
allKeys.forEach((key) => {
if (previousProps.current[key] !== props[key]) {
changesObj[key] = {
from: previousProps.current[key],
to: props[key],
};
}
});
if (Object.keys(changesObj).length) {
console.group(`[WhyDidYouUpdate] ${name}`);
console.log('Props changed:', changesObj);
console.groupEnd();
}
}
previousProps.current = props;
}); // No dependency array for useEffect means it runs after every render
}
How it works: The `useWhyDidYouUpdate` hook is a powerful debugging utility for React developers. By passing a component's `name` and its `props` to this hook, it logs to the console whenever the component re-renders, showing exactly which props have changed their values (and from what to what). This helps in identifying unnecessary re-renders, which is critical for optimizing application performance and understanding component lifecycle.