UNPKG

869 BJavaScriptView Raw
1import { useMemo } from 'react';
2const toFnRef = ref => !ref || typeof ref === 'function' ? ref : value => {
3 ref.current = value;
4};
5export function mergeRefs(refA, refB) {
6 const a = toFnRef(refA);
7 const b = toFnRef(refB);
8 return value => {
9 if (a) a(value);
10 if (b) b(value);
11 };
12}
13
14/**
15 * Create and returns a single callback ref composed from two other Refs.
16 *
17 * ```tsx
18 * const Button = React.forwardRef((props, ref) => {
19 * const [element, attachRef] = useCallbackRef<HTMLButtonElement>();
20 * const mergedRef = useMergedRefs(ref, attachRef);
21 *
22 * return <button ref={mergedRef} {...props}/>
23 * })
24 * ```
25 *
26 * @param refA A Callback or mutable Ref
27 * @param refB A Callback or mutable Ref
28 * @category refs
29 */
30function useMergedRefs(refA, refB) {
31 return useMemo(() => mergeRefs(refA, refB), [refA, refB]);
32}
33export default useMergedRefs;
\No newline at end of file