Course contentsShow
← React
Lesson 2369 of 2,39651. TypeScript with React BasicsFree lesson

Callback Refs with TypeScript

Type callback refs that receive the element as an argument instead of using useRef.

Callback Refs with TypeScript

You'll learn how to type callback refs—functions that receive DOM elements directly instead of using useRef.

What Are Callback Refs?

Instead of creating a ref object with useRef, you can pass a function directly to the ref prop. React calls this function with the DOM element when it mounts (and with null when it unmounts). This gives you more control over ref lifecycle—you can run side effects immediately when the element appears.

The Basic Pattern

A callback ref is just a function that receives the element (or null):

function MeasuredDiv() {
  const measuredRef = (element: HTMLDivElement | null) => {
    if (element) {
      console.log('Width:', element.offsetWidth);
    }
  };

  return <div ref={measuredRef}>Measured content</div>;
}

The type is simply the element type union with null because React calls your function with null during cleanup.

When to Use This Over useRef

Callback refs shine when you need to measure or interact with an element immediately when it mounts, or when the ref target might change dynamically (like in a list where you're tracking multiple elements).

function DynamicRefs() {
  const attachRef = (node: HTMLLIElement | null) => {
    if (node) {
      // Observe, measure, or manipulate immediately
      node.focus();
    }
  };

  return <li ref={attachRef}>Focus on mount</li>;
}

Key Takeaway: Type callback refs as (element: HTMLElementType | null) => void—React calls them with the element on mount and null on unmount, giving you precise lifecycle control compared to useRef.