UNPKG

@primer/components

Version:
37 lines (34 loc) 1.19 kB
import { useRef } from 'react'; import useLayoutEffect from '../utils/useIsomorphicLayoutEffect'; /** * Creates a ref by combining multiple constituent refs. The ref returned by this hook * should be passed as the ref for the element that needs to be shared. This is * particularly useful when you are using `React.forwardRef` in your component but you * also want to be able to access the local element. This is a small anti-pattern, * though, as it breaks encapsulation. * @param refs */ export function useCombinedRefs(...refs) { const combinedRef = useRef(null); useLayoutEffect(() => { function setRefs(current = null) { for (const ref of refs) { if (!ref) { return; } if (typeof ref === 'function') { ref(current); } else { ref.current = current; } } } setRefs(combinedRef.current); return () => { // ensure the refs get updated on unmount // eslint-disable-next-line react-hooks/exhaustive-deps setRefs(combinedRef.current); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [...refs, combinedRef.current]); return combinedRef; }