-
Notifications
You must be signed in to change notification settings - Fork 308
/
Copy pathrefHooks.ts
42 lines (37 loc) · 1009 Bytes
/
refHooks.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
32
33
34
35
36
37
38
39
40
41
42
import { useEffect, useRef } from 'react';
export type RefHook<T> = {
current: T;
};
export const useComparatorRef = <T>(
value: T | null | undefined,
isEqual: (v1: T | null | undefined, v2: T | null | undefined) => boolean,
onChange?: () => void
): RefHook<T | null | undefined> => {
const ref = useRef(value);
useEffect(() => {
if (!isEqual(value, ref.current)) {
ref.current = value;
if (onChange) {
onChange();
}
}
});
return ref;
};
export interface HasIsEqual<T> {
isEqual: (value: T) => boolean;
}
const isEqual = <T extends HasIsEqual<T>>(
v1: T | null | undefined,
v2: T | null | undefined
): boolean => {
const bothNull: boolean = !v1 && !v2;
const equal: boolean = !!v1 && !!v2 && v1.isEqual(v2);
return bothNull || equal;
};
export const useIsEqualRef = <T extends HasIsEqual<T>>(
value: T | null | undefined,
onChange?: () => void
): RefHook<T | null | undefined> => {
return useComparatorRef(value, isEqual, onChange);
};