-
Notifications
You must be signed in to change notification settings - Fork 94
/
index.ts
31 lines (27 loc) · 1.02 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import {type DependencyList, useEffect, useRef} from 'react';
/**
* This hook provides a console log when the component mounts, updates and unmounts.
*
* @param componentName Provides the name of the component in which the life cycle is being logged
* @param deps Dependencies list, as for `useEffect` hook
*/
export function useLifecycleLogger(componentName: string, deps?: DependencyList): void {
const mountedRef = useRef(false);
useEffect(() => {
if (mountedRef.current) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
console.log(`${componentName} updated`, deps && [...deps]);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
useEffect(() => {
mountedRef.current = true;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
console.log(`${componentName} mounted`, deps && [...deps]);
return () => {
mountedRef.current = false;
console.log(`${componentName} unmounted`);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}