Skip to content

Commit

Permalink
feat: add hook useWhyDidYouRender
Browse files Browse the repository at this point in the history
  • Loading branch information
mguellsegarra committed Sep 20, 2024
1 parent cf9386e commit 539b4dd
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/hooks/useWhyDidYouRender.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useEffect, useRef } from "react";

export function useWhyDidYouRender(componentName: string, props: any) {
const previousProps = useRef(props);

useEffect(() => {
if (previousProps.current) {
const allKeys = Object.keys({ ...previousProps.current, ...props });
const changesObj: Record<string, { old: any; new: any }> = {};
allKeys.forEach((key) => {
if (previousProps.current[key] !== props[key]) {
changesObj[key] = {
old: previousProps.current[key],
new: props[key],
};
}
});

if (Object.keys(changesObj).length) {
console.log("[why-did-you-render]", componentName, changesObj);
}
}

previousProps.current = props;
});
}

0 comments on commit 539b4dd

Please sign in to comment.