liveBook · Manning

Ref

As explained in React in Depth

A React ref is a special property that provides access to a rendered DOM node or component instance rather than being handled as an ordinary component prop.

A ref is a special React property that exposes a rendered DOM node or component instance instead of behaving like an ordinary component prop. For custom components, forwarding a ref connects an outside component to an internal element, such as an input that must receive focus. section 5.3.8

Type and route a forwarded ref explicitly:

  • Accept the ref with forwardRef in pre-React-19 functional components. section 5.3.8
  • Assign the received ref to the intended DOM element; accepting it without attaching it does not provide access. section 5.3.8
  • Type the target as Ref<HTMLInputElement> or provide HTMLInputElement and InputProps as forwardRef generic arguments. section 5.3.8
  • Use ComponentPropsWithoutRef when defining pre-React-19 component props so ref is not incorrectly modeled as an ordinary received prop. section 5.3.4

Focusing a forwarded username input

The parent creates useRef<HTMLInputElement>(null), focuses username.current in an effect, and renders <Input ref={username} label="Username" name="username" />. Input forwards the ref and renders <input ref={ref} {...rest} />, giving the parent access to the nested HTML input. section 5.3.8

import { useEffect, useRef } from "react";
import "./App.css";
import { Input } from "./Input";
export default function App() {
  const username = useRef<HTMLInputElement>(null);
  useEffect(() => {
    username.current?.focus();
  }, []);
  return (
    <main>
      <h1>Login</h1>
      <form>
        <Input ref={username} label="Username" name="username" />
        <Input label="Password" name="password" type="password" />
      </form>
    </main>
  );
}

Runnable parent component showing a typed ref, effect-driven focus, and a custom Input receiving the forwarded reference. section 5.3.8

React 19 changes the boundary: functional components can accept ref as a regular property, so forwardRef is no longer needed and ref typing becomes simpler. section 5.3.8

How React in Depth covers it

How deep it goes
Explains forwarding, DOM assignment, TypeScript errors, and two typing strategies, then notes the React 19 simplification.
Examples
Uses a login form whose parent focuses a forwarded username input after rendering.
What it assumes
Assumes React and TypeScript fundamentals while clarifying that refs are not ordinary props before React 19.
What you can do after
Build it from scratch by typing, forwarding, and attaching a ref to a custom input component.
How it connects
Connects refs with forwardRef, useRef, TypeScript generics, and ComponentPropsWithoutRef.

Also explained in

Compare how 3 books explain ref →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React in Depth. The section links point to the parts of the book it draws on.