-
-
Notifications
You must be signed in to change notification settings - Fork 31.7k
/
useForkRef.ts
27 lines (25 loc) · 888 Bytes
/
useForkRef.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
import * as React from 'react';
import setRef from './setRef';
export default function useForkRef<Instance>(
refA: React.Ref<Instance> | null | undefined,
refB: React.Ref<Instance> | null | undefined,
refC?: React.Ref<Instance> | null | undefined,
refD?: React.Ref<Instance> | null | undefined,
): React.Ref<Instance> | null {
/**
* This will create a new function if the ref props change and are defined.
* This means react will call the old forkRef with `null` and the new forkRef
* with the ref. Cleanup naturally emerges from this behavior.
*/
return React.useMemo(() => {
if (refA == null && refB == null && refC == null && refD == null) {
return null;
}
return (refValue) => {
setRef(refA, refValue);
setRef(refB, refValue);
setRef(refC, refValue);
setRef(refD, refValue);
};
}, [refA, refB, refC, refD]);
}