-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathuse-merged-ref.ts
44 lines (37 loc) · 1.1 KB
/
use-merged-ref.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
43
44
import { Ref, useCallback, type RefCallback } from 'react';
type PossibleRef<T> = Ref<T> | undefined;
type RefCleanup<T> = ReturnType<RefCallback<T>>;
export function assignRef<T>(ref: PossibleRef<T>, value: T): RefCleanup<T> {
if (typeof ref === 'function') {
return ref(value);
} else if (typeof ref === 'object' && ref !== null && 'current' in ref) {
ref.current = value;
}
}
export function mergeRefs<T>(...refs: PossibleRef<T>[]) {
const cleanupMap = new Map<PossibleRef<T>, Exclude<RefCleanup<T>, void>>();
return (node: T | null) => {
refs.forEach((ref) => {
const cleanup = assignRef(ref, node);
if (cleanup) {
cleanupMap.set(ref, cleanup);
}
});
if (cleanupMap.size > 0) {
return () => {
refs.forEach((ref) => {
const cleanup = cleanupMap.get(ref);
if (cleanup) {
cleanup();
} else {
assignRef(ref, null);
}
});
cleanupMap.clear();
};
}
};
}
export function useMergedRef<T>(...refs: PossibleRef<T>[]) {
return useCallback(mergeRefs(...refs), refs);
}