Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 83

Forwarding Refs with TypeScript

Recommended resources

Hello! Welcome to the next lesson in our module on Advanced Component and TypeScript Patterns.

In the previous lesson, we explored the historical context of Higher-Order Components (HOCs) and Render Props. We saw how they were used to share reusable logic and why they've been largely superseded by custom hooks. A key takeaway was that these patterns, especially HOCs, often act as wrappers, which can complicate the component tree and data flow.

Today, we'll address a specific limitation of this wrapping: refs. By default, a functional component cannot receive a ref. This lesson focuses on React.forwardRef, the essential utility for passing a ref from a parent component through a child to one of its underlying DOM nodes. Mastering this pattern is crucial for building truly reusable components, such as those in a component library, that need to allow imperative control from a parent.

Our goal is to understand why ref forwarding is necessary and learn how to implement it with full type safety in TypeScript.

The Problem: Refs are Not Props

First, let's establish why we need a special mechanism for this. In React, ref and key are special, reserved props. React handles them internally and does not pass them down to the component in the props object.

If you try to pass a ref to your custom functional component as if it were a regular prop, it simply won't work. React will give you a warning, and your ref will not be attached.

The following video does an excellent job of demonstrating this exact issue. It shows the intuitive but incorrect approach of passing a ref as a prop and explains why React prevents this.

A Trick Every React Developer Should Know: Ref Forwarding

Watch this segment from the video 'A Trick Every React Developer Should Know: Ref Forwarding' by Josh tried coding. It clearly illustrates the error you get when trying to pass a ref directly as a prop, setting the stage for why forwardRef is necessary.

Please watch from 00:18 to 04:21. The video will walk you through creating a parent and child component and attempting to pass a ref from parent to child via props, which results in a console warning. This demonstrates the core problem we are about to solve.

As you saw, React intercepts the ref prop. This is by design, as it prevents you from accidentally depending on the internal implementation of a child component. However, what if you are creating a generic FancyInput component and you want the parent to be able to focus the underlying <input> element? This is a valid and common use case.


The Solution: React.forwardRef

The correct way to handle this is with React.forwardRef. This is a higher-order function that you wrap your component definition in. It provides the ref passed by the parent as a second argument to your component function, separate from props.

The signature of a forwarded component looks like this:
const MyComponent = React.forwardRef((props, ref) => { ... });

Now, let's see a practical demonstration. The following video shows how a component's functionality (auto-focusing an input) breaks when it's extracted into its own component, and then how forwardRef fixes it.

Never Forget React forwardRef Again

This video, 'Never Forget React forwardRef Again' from the Coding in Public channel, provides a concise, real-world example of abstracting a form input into its own component and using forwardRef to re-enable parent control.

Watch from 03:48 to 06:04. Pay close attention to how the auto-focus functionality is lost when the input is moved to a separate Form component, and then see how wrapping the component in forwardRef and passing the ref as the second argument restores it.


Typing forwardRef with TypeScript

Now we get to the crucial part for building robust applications: adding TypeScript. Since forwardRef is a generic function, we need to provide it with type arguments to ensure everything is statically checked.

React.forwardRef takes two generic type arguments:

  1. The Ref Type: The type of the element the ref will be attached to. For an <input>, this is HTMLInputElement. For a <div>, it's HTMLDivElement.
  2. The Props Type: The type of your component's own props interface.

Let's put this together in a complete, typed example.

import React, { useRef, forwardRef } from 'react';

// 1. Define the component's props
interface FancyInputProps {
  label: string;
}

// 2. Define the component using forwardRef
const FancyInput = forwardRef<HTMLInputElement, FancyInputProps>(
  (props, ref) => {
    const { label } = props;
    
    return (
      <div style={{ margin: '10px 0' }}>
        <label style={{ marginRight: '10px' }}>{label}</label>
        {/* 3. Forward the ref to the DOM element */}
        <input ref={ref} />
      </div>
    );
  }
);

// It's good practice for debugging to set a display name
FancyInput.displayName = 'FancyInput';

// 4. Use the component in a parent
export default function ParentComponent() {
  // 5. Create a ref, specifying the element type
  const inputRef = useRef<HTMLInputElement>(null);

  const handleFocusClick = () => {
    // TypeScript knows inputRef.current can be an HTMLInputElement
    inputRef.current?.focus();
  };

  return (
    <div>
      <h3>Parent Component</h3>
      <FancyInput ref={inputRef} label="Your Name:" />
      <button onClick={handleFocusClick}>Focus the Input</button>
    </div>
  );
}

In this code, we explicitly tell forwardRef that it will be forwarding a ref to an HTMLInputElement and that its props will conform to the FancyInputProps interface. This gives us full type safety and autocompletion in both the parent and child components.

For a deeper dive into the typing options, the following article is an excellent reference.

React forwardRef: Usage, alternatives, & React 19 update

The LogRocket article 'React forwardRef: Usage, alternatives, & React 19 update' has a dedicated section on TypeScript that is very helpful. It explains the generic approach we just used and presents an alternative syntax.

Please read the section titled 'How to use forwardRef with TypeScript'. It reinforces the pattern we just discussed and shows a second valid way to type the component by annotating the callback parameters directly.

Test your understanding!

Create a FancyButton component that forwards a ref to the underlying <button> element. It should accept a children prop to define the button's text.

Then, in a parent component, use this FancyButton and create a second button that, when clicked, programmatically triggers a "click" on the FancyButton.

Hint: You can call ref.current.click() to simulate a click on a button element.

Show answer

Here's a possible solution:

import React, { useRef, forwardRef, ReactNode } from 'react';

// Prop types for the button
interface FancyButtonProps {
  children: ReactNode;
}

// The FancyButton component with forwardRef
const FancyButton = forwardRef<HTMLButtonElement, FancyButtonProps>(
  ({ children }, ref) => {
    return (
      <button ref={ref} style={{ padding: '10px', fontSize: '16px' }}>
        {children}
      </button>
    );
  }
);
FancyButton.displayName = 'FancyButton';

// Parent component to test the functionality
export default function ButtonParent() {
  const fancyButtonRef = useRef<HTMLButtonElement>(null);

  const handleTriggerClick = () => {
    console.log("Programmatically clicking the FancyButton!");
    fancyButtonRef.current?.click();
  };

  const onFancyButtonClick = () => {
    alert("FancyButton was clicked!");
  };

  return (
    <div>
      {/* Attach an onClick to the button to prove it's being clicked */}
      <div onClick={onFancyButtonClick}>
          <FancyButton ref={fancyButtonRef}>
            I'm a Fancy Button
          </FancyButton>
      </div>

      <button onClick={handleTriggerClick} style={{ marginTop: '10px' }}>
        Trigger Fancy Button Click
      </button>
    </div>
  );
}

In this solution, FancyButton correctly forwards the ref to the HTMLButtonElement. The parent component ButtonParent can then hold a reference to that DOM node and call its native methods like .click().


Advanced Pattern: useImperativeHandle

Sometimes, you don't want to expose the entire DOM element to the parent. Doing so creates a tight coupling; the parent might rely on internal details of your component's DOM structure.

React provides the useImperativeHandle hook to solve this. It's used inside a component that has been wrapped with forwardRef to let you expose a custom, limited API to the parent instead of the full DOM node.

For example, you could create a custom input component that only exposes focus() and clear() methods, nothing else.

Let's look at how to implement this.

import React, { useRef, forwardRef, useImperativeHandle } from 'react';

// 1. Define the custom API you want to expose
export interface CustomInputHandle {
  focus: () => void;
  clearAndFocus: () => void;
}

// Component props
interface CustomInputProps {
  label: string;
}

// 2. Use the custom handle type as the first generic argument
const CustomInput = forwardRef<CustomInputHandle, CustomInputProps>(
  ({ label }, ref) => {
    // This ref is internal to the component and holds the actual DOM node
    const internalInputRef = useRef<HTMLInputElement>(null);

    // 3. useImperativeHandle connects the parent's ref to your custom object
    useImperativeHandle(ref, () => ({
      focus: () => {
        internalInputRef.current?.focus();
      },
      clearAndFocus: () => {
        if (internalInputRef.current) {
          internalInputRef.current.value = '';
          internalInputRef.current.focus();
        }
      }
    }), []); // Dependencies array works just like useEffect

    return (
      <div>
        <label>{label}</label>
        <input ref={internalInputRef} />
      </div>
    );
  }
);
CustomInput.displayName = 'CustomInput';


// Parent component usage
export default function ImperativeParent() {
  // 4. The parent's ref is typed with the custom handle
  const customInputRef = useRef<CustomInputHandle>(null);

  return (
    <div>
      <CustomInput ref={customInputRef} label="API Input:" />
      <button onClick={() => customInputRef.current?.focus()}>Focus</button>
      <button onClick={() => customInputRef.current?.clearAndFocus()}>Clear & Focus</button>
    </div>
  )
}

This pattern is extremely powerful for creating component library APIs because it provides a clean boundary. You, as the component author, control exactly which imperative actions the parent can perform, preventing misuse and making future refactoring safer.


Conclusion

Today you've added a critical tool to your advanced React toolkit. While props and state are the primary way to communicate between components, forwardRef provides a controlled escape hatch for the few cases where a parent needs direct, imperative access to a child's DOM node.

Key Takeaways:

  • Reserved Prop: ref is a reserved keyword in React and cannot be passed as a standard prop.
  • The Solution: React.forwardRef is a higher-order component that passes the ref as a second argument to your component function.
  • TypeScript Typing: Correctly typing forwardRef requires two generics: forwardRef<RefElementType, PropsType>. This ensures full type safety.
  • Imperative API: You can combine forwardRef with the useImperativeHandle hook to expose a custom, limited API to the parent, hiding the underlying DOM implementation details. This is a best practice for reusable library components.

Preview of the Next Lesson:
Our journey into reusable components continues. We've seen how to make a component's API flexible with compound components and how to make it controllable with forwardRef. In the next lesson, we will explore another dimension of reusability by learning how to create generic components in TypeScript. This will allow us to build components like a type-safe <List /> that can render any kind of data, further enhancing our ability to write scalable and maintainable code.