reactuals
Version:
A useful package providing a collection of 50+ React hooks and utilities to simplify React development.
26 lines (25 loc) • 761 B
JavaScript
import { useEffect, useRef } from "react";
/**
* Logs why a component re-rendered by comparing props.
*
* @param name - Component name (for logs)
* @param props - Props to track
*
* Example:
* useWhyDidYouUpdate("MyComponent", props);
*/
export function useWhyDidYouUpdate(name, props) {
const prevProps = useRef(props);
useEffect(() => {
const changes = {};
Object.keys(props).forEach((key) => {
if (prevProps.current[key] !== props[key]) {
changes[key] = { from: prevProps.current[key], to: props[key] };
}
});
if (Object.keys(changes).length > 0) {
console.log(`[why-did-you-update] ${name}`, changes);
}
prevProps.current = props;
});
}