Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React useRef: DOM Access, Mutable Values, and Ref Forwarding

A ref holds a value for the lifetime of the component without re-rendering. When to reach for the DOM, and how refs behave in React 19.

~4 min readReact
#React#Hooks#DOM
3D illustration of persistent mutable current-reference boxes connecting directly to DOM nodes

Quick Summary

useRef(initialValue) returns a plain object with one mutable property, current, that keeps its identity for the lifetime of the component. Writing to ref.current does not schedule a render — that is the feature, not a gap. It is how a component holds a value across renders when the value itself is not part of what is displayed.

Two uses dominate. A DOM ref gives direct access to an element after React commits it, for focus, measurement, scrolling, or integrating a non-React library. A mutable instance value holds a timer id, a socket, a previous value, or an "is mounted" flag without causing renders.

The rules are short but strict. Do not read or write ref.current during render, because render must stay pure and may run twice in StrictMode. Do not use a ref where a render needs to reflect the change — that is state. And in React 19, function components receive ref as an ordinary prop, so forwardRef is no longer required to expose a DOM node; useImperativeHandle is still the way to expose a custom API.

Basic Syntax & Signature

tsx
import { useEffect, useRef } from "react"; export function SearchField() { // DOM ref: initial null, typed to the element. const inputRef = useRef<HTMLInputElement>(null); // Mutable instance value: no DOM, no rendering. const timerRef = useRef<number | null>(null); // Previous value across renders. const renders = useRef(0); useEffect(() => { // After commit, the element exists. inputRef.current?.focus(); renders.current += 1; }, []); function startDebounce() { if (timerRef.current !== null) window.clearTimeout(timerRef.current); timerRef.current = window.setTimeout(() => { console.log("debounced"); }, 300); } return ( <div> <input ref={inputRef} placeholder="type…" /> <button onClick={startDebounce}>debounce</button> <p>renders: {renders.current}</p> </div> ); }

React 19 makes ref a normal prop on function components:

tsx
// React 19: no forwardRef needed. import type { ComponentProps } from "react"; export function FancyInput({ ref, ...props }: ComponentProps<"input">) { return <input ref={ref} {...props} className="fancy" />; } // React 18 and earlier, still supported: import { forwardRef } from "react"; export const LegacyInput = forwardRef<HTMLInputElement, ComponentProps<"input">>( (props, ref) => <input ref={ref} {...props} className="fancy" />, );

Exposing a custom imperative API instead of the raw node:

tsx
import { useImperativeHandle, useRef } from "react"; type Handle = { focusAndSelect: () => void }; import type { Ref } from "react"; export function Editor({ ref }: { ref?: Ref<Handle> }) { const inputRef = useRef<HTMLInputElement>(null); useImperativeHandle(ref, () => ({ focusAndSelect() { inputRef.current?.focus(); inputRef.current?.select(); }, }), []); return <input ref={inputRef} />; }

Key Comparison Table

useRefuseStateModule-level variable
Survives re-renderYesYesYes (shared by all instances)
Triggers re-render on changeNoYesNo
Per component instanceYesYesNo
Readable on the serverYes, but no DOMYesYes
Safe to read during renderNo (except lazy init)YesNo, for mutable data
Typical contentDOM node, timer id, socketDisplayed dataConstants, caches
Ref kindType (React 19)Set by
useRef<HTMLDivElement>(null)RefObject<HTMLDivElement | null>React on commit
useRef(0)RefObject<number>Your code
createRef<T>()RefObject<T | null>Class components / unusual cases
Callback ref(node: T | null) => void | (() => void)React, with node then cleanup
useImperativeHandleWhatever handle you returnThe hook, when the parent ref is set

Practical Edge Cases & Deep Dives

1. Ref timing: null during render, set before effects

tsx
import { useLayoutEffect, useRef, useState } from "react"; function Measure() { const boxRef = useRef<HTMLDivElement>(null); const [width, setWidth] = useState(0); // Wrong: during render the node may not exist yet, and reading layout here // breaks purity and SSR. // const w = boxRef.current?.offsetWidth ?? 0; // Right: measure after commit. useLayoutEffect avoids a visible flicker. useLayoutEffect(() => { if (!boxRef.current) return; setWidth(boxRef.current.getBoundingClientRect().width); }, []); return ( <div> <div ref={boxRef} style={{ width: "50%" }}>content</div> <p>{width}px</p> </div> ); }

React attaches refs during the commit phase, before useLayoutEffect runs, so a layout effect can always read ref.current. A plain useEffect also sees the node, but the measurement happens after paint, which can cause a frame of wrong layout.

2. The "latest callback" pattern without re-subscribing

tsx
function useEventListener(type: string, handler: (e: Event) => void) { const handlerRef = useRef(handler); // Keep the ref current without making the subscription depend on it. useEffect(() => { handlerRef.current = handler; }); useEffect(() => { const listener = (e: Event) => handlerRef.current(e); window.addEventListener(type, listener); return () => window.removeEventListener(type, listener); }, [type]); } function Page() { const [count, setCount] = useState(0); useEventListener("resize", () => console.log("resize", count)); return <button onClick={() => setCount((c) => c + 1)}>{count}</button>; }

Without the ref, the subscription effect would need handler in its dependencies, and an inline handler is new on every render — the listener would be removed and re-added constantly. The ref breaks the identity chain while still delivering the newest closure. The write belongs in an effect, not in render, because a render may be discarded.

3. Callback refs and React 19 cleanup functions

tsx
function AutoScroll() { const [height, setHeight] = useState(0); // React calls this with the node on mount and with null on unmount. const measureRef = (node: HTMLDivElement | null) => { if (node) setHeight(node.scrollHeight); }; // React 19: a callback ref may return a cleanup function. const observeRef = (node: HTMLDivElement | null) => { if (!node) return; const observer = new ResizeObserver(() => setHeight(node.scrollHeight)); observer.observe(node); return () => observer.disconnect(); }; return <div ref={observeRef}>{height}</div>; }

Before React 19, returning anything from a ref callback was an error, so observers had to be tracked in a ref and torn down in an effect. The cleanup form keeps the setup and teardown in one place and runs when the node is removed or the ref callback identity changes.

4. useImperativeHandle for a controlled external API

tsx
import { useImperativeHandle, useRef } from "react"; type PlayerHandle = { play: () => void; pause: () => void; isPlaying: () => boolean }; function VideoPlayer({ ref, src }: { ref?: Ref<PlayerHandle>; src: string }) { const videoRef = useRef<HTMLVideoElement>(null); const playingRef = useRef(false); useImperativeHandle(ref, () => ({ play() { playingRef.current = true; void videoRef.current?.play(); }, pause() { playingRef.current = false; videoRef.current?.pause(); }, isPlaying: () => playingRef.current, }), []); return <video ref={videoRef} src={src} />; } function App() { const player = useRef<PlayerHandle>(null); return ( <> <VideoPlayer ref={player} src="/clip.mp4" /> <button onClick={() => player.current?.play()}>play</button> </> ); }

The dependency array of useImperativeHandle matters exactly as in useMemo: an empty array means the handle object is created once and keeps its identity, so the methods must read mutable refs rather than closed-over props. With [src] the handle is recreated when src changes and the parent's player.current updates.

5. A previous-value ref, and why it belongs in an effect

tsx
function usePrevious<T>(value: T): T | undefined { const ref = useRef<T | undefined>(undefined); useEffect(() => { ref.current = value; }, [value]); return ref.current; } function Price({ value }: { value: number }) { const prev = usePrevious(value); const direction = prev === undefined ? "flat" : value > prev ? "up" : "down"; return <p>{value} ({direction})</p>; }

usePrevious returns the value from the previous committed render because the effect that updates the ref runs after render. Writing ref.current = value in the render body would return the current value in the same pass and break the hook during StrictMode's double render.

6. Lazy initialization of a mutable object during render

tsx
function ExpensiveThing() { const cacheRef = useRef<Map<string, number> | null>(null); // Legitimate render-phase ref write: initialize once, then reuse. if (cacheRef.current === null) { cacheRef.current = new Map(); } const cache = cacheRef.current; cache.set("visited", (cache.get("visited") ?? 0) + 1); return <p>{cache.get("visited")}</p>; }

This is the one render-phase write React documents as acceptable, because the write is idempotent: a second StrictMode render finds a non-null map and skips the assignment. Mutating the map during render is still impure in a strict sense; the safer version creates the resource in useState's lazy initializer or in an effect.

Common Compilation/Runtime Mistakes

SymptomCauseFix
ref.current is null in the render bodyNode not attached yetRead it in an effect or a handler
Type error: RefObject<HTMLDivElement> not assignable to Ref<HTMLDivElement>React 18 typing without nulluseRef<HTMLDivElement>(null), or MutableRefObject
UI does not update after ref.current++Ref changes do not renderUse state for displayed values
Value resets on every renderRef created conditionally or inside a loopCall hooks unconditionally at the top level
forwardRef warning about ref propReact 19 passes ref as a propDrop forwardRef, accept ref in props
"Cannot update a component while rendering"Writing state from a render-phase ref callbackMove the write into an effect
Ref callback runs twice in StrictModeIntentional dev double invokeMake setup idempotent and use the cleanup form
useImperativeHandle exposes stale propsEmpty deps with closed-over valuesRead from refs, or add the deps
Same ref shared by two componentsRef created outside the componentCreate it inside, or pass it explicitly
Hydration mismatch with a ref-read valueServer has no DOMRender a stable placeholder until after mount

A last distinction worth keeping: useRef for a DOM node is a bridge to an imperative API, and every bridge is a place where React's model stops applying. Keep refs at the edges — focus, scroll, measurement, third-party widgets — and keep the data flow inside state and props. When a component needs a ref to make its own rendering correct, that is usually a sign the value belongs in state instead.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.