State has two jobs: it remembers a value between renders, and changing it renders the component again. Sometimes you want only the first job. A timer id, the previous value of a prop, a DOM node you need to focus: these must survive re-renders, but changing them shouldn't redraw anything, and they shouldn't be frozen into a snapshot. That's what refs are for.
This chapter covers useRef as a plain mutable box, refs to DOM nodes, passing refs as props (new in React 19, which makes forwardRef legacy), ref callbacks with cleanup, useImperativeHandle, and Fragment refs from React 19.3.
The problem: a timer you can't stop#
Here's a stopwatch. Start it, then press Stop.
import { useState } from "react";
export default function Stopwatch() {
const [startTime, setStartTime] = useState<number | null>(null);
const [now, setNow] = useState<number | null>(null);
let intervalId: number | undefined;
function handleStart() {
setStartTime(Date.now());
setNow(Date.now());
intervalId = setInterval(() => setNow(Date.now()), 10);
}
function handleStop() {
clearInterval(intervalId); // which intervalId?
}
const seconds = startTime != null && now != null ? (now - startTime) / 1000 : 0;
return (
<>
<h2>{seconds.toFixed(2)}s</h2>
<button onClick={handleStart}>Start</button> <button onClick={handleStop}>Stop</button>
</>
);
}It keeps running. handleStart stored the id in a local variable of the render it came from. The interval then caused new renders, and each new render started with let intervalId undefined. The Stop button you click belongs to the latest render, whose intervalId was never set.
Could you put the id in state? It would work, but it's the wrong tool: the id isn't shown anywhere, so storing it shouldn't trigger a render, and the interval callback would see a snapshot of it. You want a value that persists across renders, that you can change at any time, and that never causes a render.
Build it: a ref is a box in a hook slot#
You already have everything needed. A hook slot on the fiber persists across renders (Hooks from scratch). Store an object there and never call the setter, and you get a box whose identity is stable and whose contents you can change freely:
function useMyRef<T>(initial: T) {
const [box] = useState(() => ({ current: initial }));
return box; // same object every render; mutating .current doesn't render
}That's genuinely how useRef behaves (React keeps the object in its own hook slot rather than going through useState, but the semantics are the same). Now fix the stopwatch with the real hook:
import { useRef, useState } from "react";
export default function Stopwatch() {
const [startTime, setStartTime] = useState<number | null>(null);
const [now, setNow] = useState<number | null>(null);
const intervalRef = useRef<number | null>(null);
function handleStart() {
setStartTime(Date.now());
setNow(Date.now());
if (intervalRef.current !== null) clearInterval(intervalRef.current);
intervalRef.current = setInterval(() => setNow(Date.now()), 10);
}
function handleStop() {
if (intervalRef.current !== null) clearInterval(intervalRef.current);
intervalRef.current = null;
}
const seconds = startTime != null && now != null ? (now - startTime) / 1000 : 0;
return (
<>
<h2>{seconds.toFixed(2)}s</h2>
<button onClick={handleStart}>Start</button> <button onClick={handleStop}>Stop</button>
</>
);
}Every render gets the same intervalRef object, so Stop reads what Start wrote, no matter how many renders happened in between. Starting twice also clears the old interval first, which the buggy version didn't.
useRef: the mutable box#
const ref = useRef(initialValue); // { current: initialValue }- React returns the same object on every render. Only
.currentchanges, and only when you change it. - Changing
.currentdoesn't schedule a render. React doesn't know you did it. - Typing pattern:
useRef<number | null>(null)gives aRefObject<number | null>whosecurrentyou can assign. React 19's types require an argument (useRef()with no argument is a type error now) and madecurrentmutable on theRefObjectthatuseRefnow always returns;MutableRefObjectis deprecated, so the old split between it and a read-onlyRefObjectno longer matters.
import { useRef, useState } from "react";
import { Rendered } from "guide-tools";
export default function App() {
const clicksRef = useRef(0);
const [, forceRender] = useState(0);
return (
<Rendered label="App">
<p>clicksRef.current shown at the last render: {clicksRef.current}</p>
<button onClick={() => (clicksRef.current += 1)}>Count in the ref</button>{" "}
<button onClick={() => forceRender((n) => n + 1)}>Re-render</button>
</Rendered>
);
}Click the first button a few times: no flash, no change. Click Re-render and the screen catches up with whatever the ref holds. That's also why showing ref.current in JSX is a bad idea: the screen only shows it when something else happens to render.
Refs versus state#
| State | Ref | |
|---|---|---|
| Survives re-renders | Yes | Yes |
| Changing it re-renders | Yes | No |
| Inside one render | A frozen snapshot | Whatever was last written, live |
| Change it during render | No (use the setter outside render) | No (except lazy initialization) |
| Use for | Anything the UI shows | Timer ids, DOM nodes, instances, latest-value boxes |
The middle row is the important one. State gives you a snapshot; a ref gives you the latest value. That's why refs are the answer to "I need the current value inside an old callback" from State.
Don't read or write refs during render#
Render must be pure (Components and props), and a ref is mutable state React doesn't track. Reading ref.current during render makes your output depend on something that isn't props, state or context; writing it during render is a side effect that runs again if React retries the render. Read and write refs in event handlers and effects.
One exception is allowed: lazily creating an expensive object once.
const playerRef = useRef<VideoPlayer | null>(null);
if (playerRef.current === null) {
playerRef.current = new VideoPlayer(); // runs only on the first render
}The React Compiler and its lint rules flag ref access during render, so this matters more once you adopt it (The React Compiler).
Refs to DOM nodes#
The most common ref holds a DOM node. Pass the ref object as the ref prop of a built-in element and React fills in .current after it creates the node:
import { useRef } from "react";
import { books } from "guide-tools";
export default function App() {
const inputRef = useRef<HTMLInputElement>(null);
const lastRef = useRef<HTMLLIElement>(null);
return (
<>
<input ref={inputRef} placeholder="Search books" />{" "}
<button onClick={() => inputRef.current?.focus()}>Focus search</button>{" "}
<button onClick={() => lastRef.current?.scrollIntoView({ behavior: "smooth", block: "nearest" })}>Scroll to last</button>
<ul style={{ height: 120, overflow: "auto", border: "1px solid #d6d3d1" }}>
{books.map((b, i) => (
<li key={b.id} ref={i === books.length - 1 ? lastRef : undefined}>
{b.title}
</li>
))}
</ul>
</>
);
}Typing pattern: give the element type and pass null: useRef<HTMLInputElement>(null). The current type is HTMLInputElement | null, which is honest: it's null until the node exists, and again after it unmounts. Use optional chaining or a null check.
When exactly is the node there? React sets refs during the commit, after it has updated the DOM and before layout effects run. During render it's null on the first render and possibly stale on later ones.
Render. React calls your component. <input ref={inputRef} /> is just an element with a ref prop. On the first render there is no input yet, so inputRef.current is null.
Use DOM refs for things React doesn't model: focus, selection, scroll position, measuring, media playback, and integrating non-React widgets. Don't use them to change what React renders (setting textContent, removing children). React doesn't know you did it and will either overwrite you or crash when it tries to update nodes you moved.
Passing a ref to your own component React 19.0#
A ref on a built-in element gives you the DOM node. A ref on your own component used to give you nothing, because function components have no instance. React 19 made ref a regular prop for function components: whatever the parent passes as ref arrives in props, and you decide where it goes.
import { useRef, type ComponentProps } from "react";
// ComponentProps<"input"> includes ref in React 19's types.
function TextField({ label, ref, ...inputProps }: ComponentProps<"input"> & { label: string }) {
return (
<label style={{ display: "block", margin: "6px 0" }}>
{label}: <input ref={ref} {...inputProps} />
</label>
);
}
export default function App() {
const titleRef = useRef<HTMLInputElement>(null);
return (
<form onSubmit={(e) => e.preventDefault()}>
<TextField label="Title" ref={titleRef} />
<TextField label="Author" />
<button type="button" onClick={() => titleRef.current?.focus()}>
Edit title
</button>
</form>
);
}Typing pattern: for a component that wraps one element, ComponentProps<"input"> already includes ref, so spreading the rest works. For a custom shape, add ref?: Ref<HTMLInputElement> to your props type. Ref<T> accepts both ref objects and callbacks.
forwardRef is legacy Legacy#
Before 19, the same component needed forwardRef, because ref was stripped from props:
import { forwardRef } from "react";
const TextField = forwardRef<HTMLInputElement, { label: string }>(function TextField({ label }, ref) {
return (
<label>
{label}: <input ref={ref} />
</label>
);
});It still works in React 19, and you'll read it in plenty of codebases and libraries, but new code doesn't need it. The React team has said it plans to deprecate and eventually remove forwardRef in a future version. One difference worth knowing: with forwardRef the ref came as a second argument; with ref-as-prop it's just props.ref.
Ref callbacks, and cleanup in React 19 React 19.0#
Instead of an object, you can pass a function as ref. React calls it with the DOM node when it attaches. This is useful when you need to do something per node, or when you don't know in advance how many nodes there are, like a ref for every item in a list.
React 19 lets a ref callback return a cleanup function, the same shape as an effect. React calls the cleanup when the node is detached. Before 19, React signaled detachment by calling your callback again with null; when you return a cleanup, React skips that null call.
import { useState } from "react";
import { books } from "guide-tools";
// Defined outside the component, so its identity is stable across renders.
function trackSize(node: HTMLLIElement) {
const observer = new ResizeObserver(([entry]) => {
console.log(`${node.dataset.title}: ${Math.round(entry.contentRect.width)}px wide`);
});
observer.observe(node);
console.log("attached", node.dataset.title);
return () => {
observer.disconnect();
console.log("cleaned up", node.dataset.title);
};
}
export default function App() {
const [count, setCount] = useState(2);
const [wide, setWide] = useState(false);
return (
<>
<button onClick={() => setCount((c) => Math.min(c + 1, books.length))}>Add</button>{" "}
<button onClick={() => setCount((c) => Math.max(c - 1, 0))}>Remove</button>{" "}
<button onClick={() => setWide((w) => !w)}>Toggle width</button>
<ul style={{ width: wide ? 360 : 240 }}>
{books.slice(0, count).map((b) => (
<li key={b.id} ref={trackSize} data-title={b.title}>
{b.title}
</li>
))}
</ul>
</>
);
}Add and remove items and watch each observer get created and disconnected with its node. Toggle the width and every observer reports.
Two details make this work:
- Identity matters. React compares the ref callback between renders. If it's a new function (an inline arrow), React runs the old cleanup and calls the new callback on every render. That's correct but wasteful, and surprising if the callback does real work. Define it outside the component, or memoize it with
useCallback(Memoization). - Typing pattern: in React 19's types, a ref callback may return a cleanup function or nothing. An implicit return like
ref={(node) => (instance = node)}now fails to type-check, because it returns the node. Use a block body:ref={(node) => { instance = node; }}.
useImperativeHandle: expose a smaller API#
Passing your input's ref straight through gives the parent the whole DOM node. Sometimes you'd rather expose a few methods and keep the rest private, so the parent can't restyle or remove your node. useImperativeHandle sets what the parent's ref receives:
import { useImperativeHandle, useRef, type Ref } from "react";
export type SearchBoxHandle = { focus: () => void; clear: () => void };
function SearchBox({ ref }: { ref?: Ref<SearchBoxHandle> }) {
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(
ref,
() => ({
focus: () => inputRef.current?.focus(),
clear: () => {
if (inputRef.current) inputRef.current.value = "";
},
}),
[], // recreate the handle only when these change
);
return <input ref={inputRef} placeholder="Search" />;
}The parent writes const searchRef = useRef<SearchBoxHandle>(null) and calls searchRef.current?.focus(). The third argument is a dependency list, like an effect's: the handle is recreated when a dependency changes.
Keep imperative handles for things that really are imperative: focus, scroll, play, measure, open a native dialog. If you find yourself exposing setValue or open() for something the parent could pass as a prop (value, isOpen), use the prop. Declarative props are easier to reason about than a parent poking at a child.
Fragment refs React 19.3#
Sometimes you need a handle on a group of children without adding a wrapper element: a layout where an extra div would break CSS grid or a table, or a reusable component that wraps whatever it's given. React 19.3 lets <Fragment> take a ref, and the value is a FragmentInstance that acts on the fragment's DOM children.
Its methods mirror DOM APIs:
addEventListener,removeEventListener,dispatchEvent: listeners go on every first-level DOM child (components are looked through; nodes nested inside those children aren't targeted).focus()andfocusLast(): focus the first or last focusable node, searching nested children depth-first.blur()removes focus if it's inside the fragment.observeUsing(observer)andunobserveUsing(observer): attach anIntersectionObserverorResizeObserverto every first-level child.getClientRects(),getRootNode(),compareDocumentPosition(), andscrollIntoView(alignToTop?)(a boolean only; an options object throws).
import { Fragment, useRef, useState, type FragmentInstance, type ReactNode } from "react";
function Toolbar({ children }: { children: ReactNode }) {
const groupRef = useRef<FragmentInstance>(null);
const [listening, setListening] = useState(false);
function startListening() {
groupRef.current?.addEventListener("click", (e) => {
console.log("clicked:", (e.currentTarget as HTMLElement).textContent);
});
setListening(true);
}
return (
<>
<div style={{ display: "flex", gap: 6, marginBottom: 8 }}>
{/* No wrapper element of its own: the buttons stay direct flex children. */}
<Fragment ref={groupRef}>{children}</Fragment>
</div>
<button onClick={() => groupRef.current?.focus()}>Focus first</button>{" "}
<button onClick={() => groupRef.current?.focusLast()}>Focus last</button>{" "}
<button onClick={() => console.log("rects:", groupRef.current?.getClientRects().length)}>Count rects</button>{" "}
<button onClick={startListening} disabled={listening}>
Log clicks
</button>
</>
);
}
export default function App() {
const [extra, setExtra] = useState(false);
return (
<>
<Toolbar>
<button>Bold</button>
<button>Italic</button>
{extra && <button>Underline</button>}
</Toolbar>
<p>
<label>
<input type="checkbox" checked={extra} onChange={(e) => setExtra(e.target.checked)} /> Show Underline
</label>
</p>
</>
);
}Press Log clicks, then click Bold and Italic. Now tick Show Underline and click the new button: it logs too, because React adds the fragment's listeners to children inserted later (and removes them from children that leave). Focus last moves to Underline once it exists, and Count rects follows the number of children. All of it without a wrapper element around the buttons.
Typing pattern: FragmentInstance is exported as a type from react, and react-dom's types fill in the DOM methods. A ref on the <> shorthand isn't possible, because it takes no props; import Fragment.
Pitfalls#
Check your understanding#
This is the stopwatch from the start of the chapter. Make Stop actually stop it, and make a second Start restart cleanly instead of stacking intervals.
import { useState } from "react";
export default function Stopwatch() {
const [startTime, setStartTime] = useState<number | null>(null);
const [now, setNow] = useState<number | null>(null);
let intervalId: number | undefined;
function handleStart() {
setStartTime(Date.now());
setNow(Date.now());
intervalId = setInterval(() => setNow(Date.now()), 10);
}
function handleStop() {
clearInterval(intervalId);
}
const seconds = startTime != null && now != null ? (now - startTime) / 1000 : 0;
return (
<>
<h2>{seconds.toFixed(2)}s</h2>
<button onClick={handleStart}>Start</button> <button onClick={handleStop}>Stop</button>
</>
);
}Make SearchBox accept a ref prop and expose exactly two methods through it with useImperativeHandle: focus() focuses the input, and clear() empties it and focuses it. The parent's buttons already call them.
import { useImperativeHandle, useRef, type Ref } from "react";
export type SearchBoxHandle = { focus: () => void; clear: () => void };
function SearchBox() {
const inputRef = useRef<HTMLInputElement>(null);
// TODO: accept a ref prop and expose { focus, clear }
return <input ref={inputRef} aria-label="Search" defaultValue="" />;
}
export default function App() {
const searchRef = useRef<SearchBoxHandle>(null);
return (
<>
<SearchBox ref={searchRef} />{" "}
<button onClick={() => searchRef.current?.focus()}>Focus</button>{" "}
<button onClick={() => searchRef.current?.clear()}>Clear</button>
</>
);
}The user clicks +1 three times, then Show. What's on screen after each step?
function App() {
const countRef = useRef(0);
const [shown, setShown] = useState(false);
return (
<>
<p>{shown ? `Count: ${countRef.current}` : "Hidden"}</p>
<button onClick={() => countRef.current++}>+1</button>
<button onClick={() => setShown(true)}>Show</button>
</>
);
}A component logs `inputRef.current` during its first render, then in a useLayoutEffect. What do the two logs show?
An interviewer asks: "What's the difference between useRef and useState, and when would you pick a ref?"
Interview angle
A ref is a mutable box, { current }, that React keeps in a hook slot and returns unchanged on every render. Changing it doesn't re-render, and it always holds the latest value rather than a snapshot. Use it for things the UI doesn't show, like timer ids or library instances, and for DOM nodes you need to focus, scroll or measure. React attaches DOM refs during commit, before layout effects, so don't read them during render. In React 19 ref is a normal prop for function components, which makes forwardRef legacy, ref callbacks can return a cleanup, and 19.3 adds refs on Fragments.
What's the difference between useRef and useState?
When does React set a DOM ref, and why can't you read it during render?
How did React 19 change passing refs to components?
What's a ref callback, and what changed about them in React 19?
When would you use useImperativeHandle?
What are Fragment refs in React 19.3, and what problem do they solve?
Recap#
useRefreturns the same{ current }object every render. Changing.currentdoesn't render, and it holds the latest value rather than a snapshot.- Use refs for values the UI doesn't show and for DOM nodes. Don't read or write them during render, except for lazy initialization.
- React attaches DOM refs during commit, before layout effects, and detaches them on unmount. On the first render they're
null. - In React 19,
refis a prop for function components (forwardRefis legacy), and ref callbacks can return a cleanup.useImperativeHandlelimits what a parent can do through the ref. - React 19.3's Fragment refs give a
FragmentInstancefor focus, listeners, observers and rects over a group of children, without a wrapper element.
Sources#
- react.dev: Referencing values with refs, Manipulating the DOM with refs
- react.dev: useRef, useImperativeHandle, forwardRef
- react.dev: Common components: ref callback function, Fragment
- react.dev blog: React 19 (ref as a prop, cleanup functions for refs) and the React 19 upgrade guide (useRef requires an argument, ref callback typing)
- Type definitions:
FragmentInstancein@types/reactand@types/react-dom19.3.1 - Facts checked November 24, 2026.