use-merged-ref

Use multiple refs for one dom node
Import

Usage

Hook accepts any amount of refs and returns function that should be passed to dom node. Use hook when you need to use more than one ref on single dom node, for example, when you want to use use-click-outside and use-focus-trap hooks and also get a ref for yourself:

import { useRef } from 'react';
import { useClickOutside, useFocusTrap, useMergedRef } from '@mantine/hooks';
function Demo() {
const myRef = useRef();
const useClickOutsideRef = useClickOutside(() => {});
const focusTrapRef = useFocusTrap();
const mergedRef = useMergedRef(myRef, useClickOutsideRef, focusTrapRef);
return <div ref={mergedRef} />;
}

mergeRefs function

useMergedRef hooks memoizes refs with useCallback hook, but in some cases memoizing is not a valid strategy, for example, when you are working with a list of dynamic components React will complain that different amount of hooks was called across two renders. To fix that issue use mergeRefs function instead:

import { useRef } from 'react';
import { useClickOutside, useFocusTrap, mergeRefs } from '@mantine/hooks';
function Demo() {
const myRef = useRef();
const useClickOutsideRef = useClickOutside(() => {});
const mergedRef = mergeRefs(myRef, useClickOutsideRef);
return <div ref={mergedRef} />;
}

mergeRefs works the same way as useMergedRef but does not use hooks internally. Use it only when you cannot use useMergedRef. Note that mergeRefs will not work correctly with use-focus-trap hook, you are required to use useMergedRef with it.

TypeScript

Definition

function useMergedRef<T = any>(...refs: React.ForwardedRef<T>[]): (node: T) => void;

Set node type

useMergedRef<HTMLDivElement>();
Build fully functional accessible web applications faster than ever
Feedback
Your feedback is most valuable contribution to the project, please share how you use Mantine, what features are missing and what is done good
Leave feedback