Skip to content

Lesson 14 of 37Effects and beyond

Refs

Use useRef to reach real DOM nodes and to keep values between renders without re-rendering.

20 min read0/7 questions

Sometimes you need to step outside React's "describe the UI" model: put the cursor in a search box, scroll a chat to the bottom, remember an interval id so a Stop button can clear it. Refs are the tool for that. Interviewers like them because the "ref vs state" question shows whether you understand what actually causes a re-render.

A box that survives renders

useRef(initial) returns a plain object, { current: initial }. React gives you the same object on every render of that component. You can read and write ref.current freely, and changing it does not trigger a re-render.

import { useRef } from "react";
 
const countRef = useRef(0);
countRef.current += 1; // no re-render, the value is just stored

Compare that with state, where each render gets its own snapshot and setting it asks React to render again.

Same box, new snapshots
render 1
NamesObjects in memorycount (state)countRefnumber0object{ current: 0 }

On the first render, state count is a snapshot of 0, and countRef points to a box holding 0.

1/3

Try it. The left button only updates a ref, so the number on screen does not move until something else causes a render.

ReactRefVsState.tsx
import { useRef, useState } from "react"; export default function App() { const clicksRef = useRef(0); const [renders, setRenders] = useState(0); return ( <div style={{ display: "grid", gap: 8, maxWidth: 320 }}> <button onClick={() => { clicksRef.current += 1; console.log("ref is now", clicksRef.current); }}> Add to ref (no render) </button> <button onClick={() => setRenders(renders + 1)}>Re-render ({renders})</button> <p>Ref value shown on screen: {clicksRef.current}</p> </div> );}
Quick check
You click Add to ref three times, then Re-render once. What does the paragraph show?
Need a nudge? A hint rules out a wrong answer.

Refs to DOM nodes

The most common use: pass a ref to a JSX element's ref attribute. After React commits that element to the page, it sets ref.current to the real DOM node. When the element is removed, React sets it back to null.

ReactFocusSearch.tsx
import { useRef } from "react"; export default function App() { const inputRef = useRef<HTMLInputElement>(null); return ( <div style={{ display: "flex", gap: 8 }}> <input ref={inputRef} type="text" placeholder="Search..." /> <button onClick={() => inputRef.current?.focus()}>Focus search</button> <button onClick={() => inputRef.current?.select()}>Select text</button> </div> );}

Things you can only do with a DOM ref: focus(), select(), scrollIntoView(), measuring with getBoundingClientRect(), playing a <video>, or handing a node to a non-React library such as a chart or map.

Refs for values that are not on screen

Refs are also the right home for mutable values that matter to your code but not to the UI. The classic case is an interval id: the Stop handler needs it, but showing it would be pointless.

ReactCountdown.tsx
import { useRef, useState } from "react"; export default function App() { const [seconds, setSeconds] = useState(10); const intervalRef = useRef<number | null>(null); function start() { if (intervalRef.current !== null) return; // already running intervalRef.current = window.setInterval(() => { setSeconds((s) => (s > 0 ? s - 1 : 0)); }, 1000); } function stop() { if (intervalRef.current !== null) window.clearInterval(intervalRef.current); intervalRef.current = null; } return ( <div> <p style={{ fontSize: 32, margin: 0 }}>{seconds}s</p> <button onClick={start}>Start</button> <button onClick={stop}>Stop</button> <button onClick={() => { stop(); setSeconds(10); }}>Reset</button> </div> );}

If you stored the id in state, setting it would cause a pointless render. If you stored it in a plain let inside the component, it would be lost on the next render, because every render runs the function from scratch.

Predict the outputJavaScript

Each click calls setTick (which re-renders) and then logs. What is logged after the third click?

function App() {
let plain = 0;
const box = useRef(0);
const [tick, setTick] = useState(0);

function handleClick() {
  plain += 1;
  box.current += 1;
  setTick(tick + 1);
  console.log(plain, box.current);
}
return <button onClick={handleClick}>Go</button>;
}
Need a nudge? Hints walk you through it.

Refs vs state

useStateuseRef
Changing it re-rendersYesNo
Value during a renderA fixed snapshotWhatever was last written
How you update itsetX(next)ref.current = next
Read it during render?Yes, that is the pointAvoid (except lazy initialization)
Good forAnything shown on screenDOM nodes, timer ids, previous values, instance flags

A good rule: if changing the value should change what the user sees, it is state. If it is bookkeeping for handlers and effects, it is a ref.

Match the pairs0/5 matched

Ref or state?

Choose an item, then its match on the other side.

Passing a ref to your own component

What if the input lives inside your own <TextField> component? Before React 19 you had to wrap the component in forwardRef. In React 19, ref is an ordinary prop for function components, so you accept it and pass it down.

ReactRefAsProp.tsx
import { useRef } from "react"; function TextField({ label, ref }: { label: string; ref?: React.Ref<HTMLInputElement> }) { return ( <label style={{ display: "grid", gap: 4 }}> {label} <input ref={ref} type="text" /> </label> );} export default function App() { const emailRef = useRef<HTMLInputElement>(null); return ( <div style={{ display: "grid", gap: 8, maxWidth: 260 }}> <TextField label="Email" ref={emailRef} /> <button onClick={() => emailRef.current?.focus()}>Jump to email</button> </div> );}

You will still see forwardRef in older code and libraries. It works in React 19, but new components do not need it.

React 19 also lets a ref callback return a cleanup function, which is handy when you attach something to a node:

<div
  ref={(node) => {
    const observer = new ResizeObserver(() => console.log("resized"));
    observer.observe(node!);
    return () => observer.disconnect(); // runs when the node is removed
  }}
/>
Quick check
A teammate writes <p>{renderCountRef.current}</p> and increments the ref in the component body to show a render counter. What is the problem?
Need a nudge? A hint rules out a wrong answer.

Ref callbacks in depth

A ref object is a box React fills in. A ref callback is a function React calls with the node, which lets you run code at the exact moment a node appears or disappears. That is the right tool when the thing you attach depends on the node itself: an observer, a third-party widget, a measurement, or a node in a list where you cannot call useRef once per item.

The React 19 lifecycle is simple once you see it:

  1. After React commits the element, it calls your callback with the DOM node.
  2. If the callback returned a function, React keeps it as the cleanup.
  3. When the node is removed, React calls the cleanup. It does not call your callback with null any more, as it did before React 19 (it still does for callbacks that return nothing).
  4. If you pass a different function on the next render, React treats it as a new ref: it runs the old cleanup, then calls the new callback.

Point 4 surprises people. An inline arrow function is a new function on every render, so it detaches and reattaches every time the component renders. Open the console and click Re-render a few times.

ReactRefCallbackLifecycle.tsx
import { useCallback, useState } from "react"; export default function App() { const [count, setCount] = useState(0); const [isShown, setIsShown] = useState(true); // Stable: same function every render, so it only runs on mount and removal. const stableRef = useCallback(() => { console.log("stable: attach"); return () => console.log("stable: cleanup"); }, []); return ( <div style={{ display: "grid", gap: 8, maxWidth: 320 }}> <button onClick={() => setCount(count + 1)}>Re-render ({count})</button> <button onClick={() => setIsShown(!isShown)}>{isShown ? "Remove" : "Add"} boxes</button> {isShown && ( <> <div ref={() => { console.log("inline: attach"); return () => console.log("inline: cleanup"); }} > Inline ref callback </div> <div ref={stableRef}>Stable ref callback</div> </> )} </div> );}

Each re-render logs inline: cleanup then inline: attach, while the stable one stays quiet until you remove the boxes. For a console.log that is harmless. For a callback that creates a ResizeObserver or boots a map library, it means tearing down and rebuilding on every keystroke. Wrap such callbacks in useCallback (or let the React Compiler do it), or move the setup into an effect that depends on a ref object.

One TypeScript detail from the React 19 upgrade: because a returned function now means "cleanup", the old shortcut ref={(node) => (inputEl = node)} is rejected by the types. The arrow returns the node, which is not a cleanup function. Use a block body: ref={(node) => { inputEl = node; }}.

Predict the outputJavaScript

This component renders once, then you click the button once. What is the full console output, in order?

function App() {
const [n, setN] = useState(0);
return (
  <button
    onClick={() => setN(n + 1)}
    ref={(node) => {
      console.log("attach");
      return () => console.log("cleanup");
    }}
  >
    {n}
  </button>
);
}
Need a nudge? Hints walk you through it.

useImperativeHandle: expose a small API, not the node

Passing your inner <input> to the parent through ref, as in the TextField example, hands over the whole DOM node. The parent can now change its styles, remove it, or read its value. For a design-system component that is often too much. useImperativeHandle lets you decide exactly what the parent's ref receives.

ReactImperativeHandle.tsx
import { useImperativeHandle, useRef, useState } from "react"; type SearchHandle = { focus: () => void; clear: () => void }; function SearchField({ ref }: { ref?: React.Ref<SearchHandle> }) { const inputRef = useRef<HTMLInputElement>(null); const [text, setText] = useState(""); useImperativeHandle(ref, () => ({ focus: () => inputRef.current?.focus(), clear: () => { setText(""); inputRef.current?.focus(); }, }), []); return <input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} placeholder="Search..." />;} export default function App() { const searchRef = useRef<SearchHandle>(null); return ( <div style={{ display: "flex", gap: 8 }}> <SearchField ref={searchRef} /> <button onClick={() => searchRef.current?.focus()}>Focus</button> <button onClick={() => searchRef.current?.clear()}>Clear</button> </div> );}

The parent can call focus() and clear() and nothing else. You are free to change the markup inside SearchField later without breaking callers, because the contract is two methods, not a DOM node.

Use this sparingly. If something can be expressed as a prop, it should be: <Modal isOpen> beats modalRef.current.open(), because props flow through rendering and stay in sync with state. Good imperative APIs are the ones that are naturally actions rather than state: focus, scroll to an item, play, pause, select all, reset a canvas. The third argument is a dependency array, like useMemo; if your handle reads props or state, list them, or the parent calls a stale function.

Measuring layout: useLayoutEffect and ResizeObserver

Tooltips, popovers, auto-growing text areas, and "show more" buttons all need the same thing: the real size or position of a node, then a render that uses it. If you measure in useEffect, the browser may paint the first, wrong position before your effect runs, and the user sees a flicker as the tooltip jumps.

useLayoutEffect has the same signature as useEffect, but React runs it after the DOM is updated and before the browser paints. State you set inside it triggers a synchronous re-render, also before paint. The user only ever sees the corrected layout.

Placing a tooltip without a flicker
ReactDOMLayout effectBrowser paintcommit tooltip at top: 0run before paintgetBoundingClientRect()setTop(measured)paint final position

React writes the tooltip with a guessed position. Nothing is on screen yet.

1/5
ReactMeasureTooltip.tsx
import { useLayoutEffect, useRef, useState } from "react"; function Tooltip({ text }: { text: string }) { const tipRef = useRef<HTMLDivElement>(null); const [height, setHeight] = useState(0); useLayoutEffect(() => { const rect = tipRef.current!.getBoundingClientRect(); setHeight(rect.height); console.log("measured tooltip height:", Math.round(rect.height)); }, [text]); return ( <div ref={tipRef} role="tooltip" style={{ position: "absolute", top: -height - 8, left: 0, width: 200, padding: 6, background: "#222", color: "#fff", fontSize: 13 }} > {text} </div> );} export default function App() { const [isLong, setIsLong] = useState(false); const text = isLong ? "A longer tip that wraps onto several lines, so its height changes and must be measured again." : "Short tip."; return ( <div style={{ position: "relative", marginTop: 110, display: "inline-block" }}> <Tooltip text={text} /> <button onClick={() => setIsLong(!isLong)}>Toggle tip length</button> </div> );}

The tooltip always sits just above the button, whatever its height. Two costs to know. Layout effects block painting, so keep them short and reserve them for measure-then-render work. And they do not run during server rendering, so the HTML from the server cannot contain the measured value; the first client render corrects it.

useLayoutEffect measures when React renders. Sizes also change when React does nothing: the window resizes, a font loads, a sidebar collapses through CSS. For those, use ResizeObserver, and attach it with a ref callback with cleanup, which is exactly the shape React 19 made easy:

function useElementWidth() {
  const [width, setWidth] = useState(0);
  const ref = useCallback((node: HTMLElement) => {
    const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));
    observer.observe(node);
    return () => observer.disconnect();
  }, []);
  return [ref, width] as const;
}
 
// const [ref, width] = useElementWidth();
// <div ref={ref}>{width > 600 ? <WideChart /> : <NarrowChart />}</div>

Prefer CSS (container queries, aspect-ratio, flex and grid) when it can do the job. Measuring in JavaScript is for the cases CSS cannot express, such as positioning relative to another element or virtualizing a list.

Quick check
A popover measures its own width in useEffect and then moves itself left so it does not overflow the screen. Users report that it visibly jumps when it opens. What is the fix?
Need a nudge? A hint rules out a wrong answer.

Fragment refs (React 19.3)

Sometimes the nodes you care about have no single parent you own. A list component renders a group of <li> items into a <ul> that belongs to its parent, or a focus trap needs to manage a group of siblings. The old fix was an extra wrapper <div>, which breaks CSS grids, flex layouts, and table markup.

React 19.3 made Fragment refs stable. You put a ref on <Fragment> and receive a FragmentInstance: an object that acts on all the DOM nodes the fragment renders, without adding any node of its own. Its methods include:

  • addEventListener / removeEventListener: listen on every top-level child at once, including children added later.
  • focus() / focusLast() / blur(): move focus to the first or last focusable element inside the group.
  • observeUsing(observer) / unobserveUsing(observer): attach an IntersectionObserver or ResizeObserver to every child.
  • getClientRects(), scrollIntoView(), compareDocumentPosition(): measure, scroll to, and order the group.
ReactFragmentRef.tsx
import { Fragment, useEffect, useRef } from "react"; function Group({ children }: { children: React.ReactNode }) { const groupRef = useRef<React.FragmentInstance>(null); useEffect(() => { const group = groupRef.current!; const onClick = (e: Event) => console.log("clicked:", (e.target as HTMLElement).textContent); group.addEventListener("click", onClick); console.log("rects in group:", group.getClientRects().length); return () => group.removeEventListener("click", onClick); }, []); return <Fragment ref={groupRef}>{children}</Fragment>;} export default function App() { return ( <ul> <li>Not in the group</li> <Group> <li>Inbox</li> <li>Drafts</li> <li>Sent</li> </Group> </ul> );}

Click the items. The three inside Group log; the first one does not, and the <ul> still contains only <li> children, so the markup stays valid. Analytics wrappers that track when a section scrolls into view, focus management in menus, and libraries that need to measure "whatever this component rendered" are the main users. In TypeScript the type is React.FragmentInstance. @types/react declares it empty and @types/react-dom adds the DOM methods, so if your editor says focus does not exist, update both type packages together.

Refs at work: the bugs you will meet

A few patterns come up again and again in code review.

Reading a ref in effect cleanup. The linter warns when cleanup reads someRef.current, because by the time cleanup runs, the ref may point at a different node or null. Copy it into a local first:

useEffect(() => {
  const node = listRef.current; // capture now
  node?.addEventListener("scroll", onScroll);
  return () => node?.removeEventListener("scroll", onScroll);
}, []);

Putting ref.current in a dependency array. Changing a ref does not re-render, so the effect does not re-run when it changes; the dependency only looks like it works. If you need to react to a node appearing, use a ref callback.

Expensive initial values. useRef(new Player()) constructs a new Player on every render and throws all but the first away. Initialise lazily:

const playerRef = useRef<Player | null>(null);
if (playerRef.current === null) playerRef.current = new Player(); // runs once

This is the one sanctioned case of writing a ref during render: it is idempotent, so double rendering in StrictMode does no harm.

A Map of refs for lists. You cannot call useRef in a loop, but you can keep one ref holding a Map and fill it from ref callbacks:

const itemsRef = useRef(new Map<string, HTMLLIElement>());
 
<li
  key={item.id}
  ref={(node) => {
    itemsRef.current.set(item.id, node!);
    return () => itemsRef.current.delete(item.id);
  }}
/>
 
// later: itemsRef.current.get(selectedId)?.scrollIntoView({ block: "nearest" });
Match the pairs0/5 matched

Match each job to the tool that fits it best.

Choose an item, then its match on the other side.
ChallengeEasy

Focus and read an input with a ref

Build an uncontrolled name field (no value, no state for the text) driven by a ref.

  • A text input (type="text").
  • Focus puts the cursor in the input.
  • Read shows You typed: <text> in a paragraph, reading the value straight from the DOM node.
  • Clear empties the input and focuses it again.

Use useRef<HTMLInputElement>(null) and attach it with ref={inputRef}.

React
import { useRef, useState } from "react"; export default function App() { // Create a ref, attach it to the input, and use inputRef.current in the handlers. return ( <div> <input type="text" placeholder="Your name" /> <button>Focus</button> <button>Read</button> <button>Clear</button> </div> );}
Key terms
ref
A { current } object from useRef that persists across renders. Changing current does not re-render.
DOM ref
A ref passed to a JSX element's ref attribute. React sets current to the DOM node after commit and back to null on removal.
uncontrolled input
An input whose value lives in the DOM rather than React state. You read it through a ref when needed.
ref as a prop
React 19 lets function components receive ref like any other prop, replacing forwardRef.
ref callback cleanup
In React 19, a function passed to ref can return a cleanup that runs when the node is detached.
useImperativeHandle
A hook that sets what a parent's ref receives, so a component can expose a few methods instead of its DOM node.
useLayoutEffect
An effect that runs after the DOM updates but before the browser paints. Used to measure layout and re-render without a flicker.
Fragment ref
A ref on <Fragment> (stable in React 19.3) that returns a FragmentInstance acting on all the DOM nodes the fragment renders.