Skip to content
Snippets Groups Projects
useMergedRefs.ts 606 B
Newer Older
  • Learn to ignore specific revisions
  • import { useCallback } from 'react';
    
    import type { MutableRefObject, Ref, RefCallback } from 'react';
    
    James Long's avatar
    James Long committed
    
    
      ...refs: (
        | RefCallback<T | null | undefined>
        | MutableRefObject<T | null | undefined>
        | Ref<T | null | undefined>
        | null
        | undefined
      )[]
    
      return useCallback(
        (value: T) => {
          [...refs].forEach(ref => {
    
    James Long's avatar
    James Long committed
            if (typeof ref === 'function') {
              ref(value);
    
            } else if (ref != null && 'current' in ref) {
              (ref as MutableRefObject<T>).current = value;
    
    James Long's avatar
    James Long committed
            }
          });
    
    James Long's avatar
    James Long committed
    }