Course contentsShow
← React
Lesson 742 of 2,39619. useRefFree lesson

Combining Multiple Ref Patterns in One Component

Use separate refs for focus, scroll, and measurement within the same component for complex interactions.

Combining Multiple Ref Patterns in One Component

What you'll learn: How to use several refs in the same component, each serving a different purpose, to create rich, interactive behaviors.

Real-world components often need multiple refs working together. You might need one ref to focus an input, another to scroll a container, and a third to measure an element's size—all in the same component. React doesn't limit you to one ref per component; you can create as many as you need.

The Multi-Ref Pattern

Each ref serves a specific purpose. Think of them like different tools in a toolbox: a screwdriver for one job, a hammer for another. They don't interfere with each other because each useRef() call creates an independent mutable container.

function ComplexForm() {
  const inputRef = useRef(null);
  const containerRef = useRef(null);
  const headerRef = useRef(null);

  const focusInput = () => {
    inputRef.current?.focus();
  };

  const scrollToTop = () => {
    containerRef.current?.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const measureHeader = () => {
    const height = headerRef.current?.getBoundingClientRect().height;
    console.log('Header height:', height);
  };

  return (
    <div ref={containerRef} style={{ height: '400px', overflow: 'auto' }}>
      <h1 ref={headerRef}>Form Title</h1>
      <input ref={inputRef} type="text" />
      <button onClick={focusInput}>Focus Input</button>
      <button onClick={scrollToTop}>Scroll Up</button>
      <button onClick={measureHeader}>Measure Header</button>
    </div>
  );
}

Each ref targets a different DOM node and enables a different capability. They coexist peacefully because they're independent variables—just like having multiple useState calls.

Key Takeaway: Use multiple refs freely within a component, each attached to different elements and serving different interaction needs—focus, scroll, measurement, or third-party library control can all coexist.