Hooks & APIs: useRef & The Direct ref Prop
useRef & Direct ref Prop: Access DOM nodes directly and take advantage of React 19's direct ref passing on function components.
- **In React, the primary mental model is declarative:** you update state, and React handles the DOM reconciliation.
However, real-world applications frequently require imperative access to the outside world—focusing input fields, calculating element layout bounds, binding non-React third-party widgets, or retaining mutable data across renders without triggering a paint pass.
React provides useRef for this exact escape hatch. Furthermore, React 19 revolutionizes how references are handled by deprecating the legacy forwardRef higher-order component and making ref a standard, first-class component prop.
## 1. The Dual Nature of useRef
The useRef hook returns a plain, mutable JavaScript container with a single property: \{ current: initialValue \}.
It serves two distinct architectural purposes:
```text
useRef(initialValue)
│
┌─────────────────────────┴─────────────────────────┐
▼ ▼
[ DOM REFERENCE ] [ MUTABLE VALUE CONTAINER ]
• Points to real HTML nodes • Stores variables across renders
• Set by React during Commit phase • Mutating .current NEVER triggers re-render
• Bypasses declarative virtual tree • Ideal for timers, IDs, previous state
```
- **DOM Node Handle:** Passed to a JSX node (<input ref=\{inputRef\} />), React populates inputRef.current with the underlying native DOM element once committed to the screen, resetting it to null on unmount.
- **Instance Variable Container:** Operates identically to an instance property on a class. Mutating ref.current updates synchronously in memory without queuing a render pass or altering the execution schedule.
### useState vs. useRef at a Glance
| Feature | useState | useRef | Updating triggers re-render? |
| --- | --- | --- | --- |
| Yes (Schedules reconciliation pass) | No (Updates synchronously in memory) | Access timing | Snapshot-based (closures capture current render state) |
| Direct reference (always reads the latest value via .current) | Primary Use Cases | Visual data rendered in JSX | Metadata, timers, cached instances, DOM handles |
## 2. Using useRef for Imperative DOM Manipulation
Direct DOM manipulation should be reserved for imperative tasks that cannot be handled declaratively.
### 2.1 The Focus & Text Selection Pattern
```ts
import { useRef } from 'react';
export function SearchBar() {
// Initialize with null; populated when mounted to the DOM
const inputRef = useRef(null);
function handleClearAndFocus() {
if (inputRef.current) {
inputRef.current.value = '';
inputRef.current.focus(); // Imperative native DOM call
}
}
return (
);
}
```
### 2.2 Measuring DOM Nodes (getBoundingClientRect)
Staging DOM nodes in a ref allows accurate layout measurement inside useLayoutEffect without requiring global document.querySelector sweeps:
```ts
import { useRef, useState, useLayoutEffect } from 'react';
export function ResponsiveBanner() {
const bannerRef = useRef(null);
const [bannerWidth, setBannerWidth] = useState(0);
useLayoutEffect(() => {
if (bannerRef.current) {
const { width } = bannerRef.current.getBoundingClientRect();
setBannerWidth(width);
}
}, []);
return (
{
label: string;
}
export const LegacyInput = forwardRef(
({ label, ...rest }, ref) => {
return (
);
}
);
LegacyInput.displayName = 'LegacyInput';
```
### 3.2 The Modern Pattern: Direct ref Prop (React 19+)
In React 19, ref is extracted directly from the props argument. No wrapper, no HOC, and no separate second function parameter:
```ts
// ✅ MODERN (React 19): Clean, direct prop destructuring
import type { ComponentPropsWithoutRef, Ref } from 'react';
interface CustomInputProps extends ComponentPropsWithoutRef<'input'> {
label: string;
ref?: Ref; // Typed directly in the interface
}
export function ModernInput({ label, ref, ...rest }: CustomInputProps) {
return (
);
}
```
Consumer Usage:
The consuming component treats custom components identically to standard native HTML tags:
```ts
import { useRef } from 'react';
import { ModernInput } from './ModernInput';
export function FormParent() {
const inputRef = useRef(null);
return (
);
}
```
## 4. Limiting Exposure: useImperativeHandle
Passing a raw DOM node ref exposes every property and method on that element (style, value, remove(), parentElement) to parent components, breaking component encapsulation boundaries.
To expose a strictly defined public interface while keeping internal DOM details private, pair the direct ref prop with useImperativeHandle:
```ts
import { useRef, useImperativeHandle, type Ref } from 'react';
// 1. Define the restricted public contract
export interface VideoPlayerHandle {
play: () => void;
pause: () => void;
seekToStart: () => void;
}
interface VideoPlayerProps {
src: string;
ref?: Ref; // Ref holds the handle interface, NOT the HTMLVideoElement
}
export function VideoPlayer({ src, ref }: VideoPlayerProps) {
const internalVideoRef = useRef(null);
// 2. Map designated methods to the incoming ref handle
useImperativeHandle(ref, () => ({
play() {
internalVideoRef.current?.play();
},
pause() {
internalVideoRef.current?.pause();
},
seekToStart() {
if (internalVideoRef.current) {
internalVideoRef.current.currentTime = 0;
}
}
}));
return ;
}
```
Consuming the Restricted Handle:
```ts
import { useRef } from 'react';
import { VideoPlayer, type VideoPlayerHandle } from './VideoPlayer';
export function MediaDashboard() {
const playerRef = useRef(null);
return (
{/* Consumer can ONLY call the explicitly exposed methods */}
);
}
```
## 5. Ref Callbacks: Managing Dynamic Collections
You cannot call useRef inside a loop or array iteration because it violates the Rules of Hooks. When you need to reference a variable number of elements in a dynamic list, use a Ref Callback.
Instead of a ref object, pass a callback function to the ref prop:
```ts
Current container width: {bannerWidth}px
);
}
```
## 3. The React 19 Paradigm Shift: Direct ref as a Prop
Before React 19, functional components could not accept a ref prop directly. Passing a ref to a custom component threw runtime warnings, forcing developers to wrap their components in the forwardRef higher-order component.
- **React 19 deprecates forwardRef entirely:** ref is now a standard, first-class prop on functional components, just like children or key.
### 3.1 The Legacy Pattern: forwardRef (React 18 & Earlier)
```ts
// ❌ LEGACY (React 18): Boilerplate forwardRef HOC
import { forwardRef } from 'react';
interface CustomInputProps extends React.InputHTMLAttributes { /* Handle registration / cleanup */ }} />
```
React calls this function with the DOM node when it mounts, and calls it with null when it unmounts.
Managing Dynamic Lists via a Map Ref:
```ts
import { useRef } from 'react';
export function ItemList({ items }: { items: { id: string; text: string }[] }) {
// Store a collection of DOM nodes in a Map inside a single ref
const itemsMapRef = useRef
