Skip to content

Commit de16e31

Browse files
committed
feat(hooks): add useWhyDidYouUpdate hook
1 parent 4986e5d commit de16e31

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

lib/hooks/useWhyDidYouUpdate.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use client';
2+
import { useEffect, useRef } from 'react';
3+
export function useWhyDidYouUpdate<T extends Record<string, unknown>>(name: string, props: T): void {
4+
const previousProps = useRef<T>();
5+
useEffect(() => {
6+
if (previousProps.current) {
7+
const allKeys = Object.keys({ ...previousProps.current, ...props });
8+
const changes: Record<string, { from: unknown; to: unknown }> = {};
9+
allKeys.forEach(key => {
10+
if (previousProps.current![key] !== props[key]) {
11+
changes[key] = { from: previousProps.current![key], to: props[key] };
12+
}
13+
});
14+
if (Object.keys(changes).length) console.log('[why-update]', name, changes);
15+
}
16+
previousProps.current = props;
17+
});
18+
}

0 commit comments

Comments
 (0)