Lesson 14 of 37Effects and beyond
Refs
Use useRef to reach real DOM nodes and to keep values between renders without re-rendering.
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 storedCompare that with state, where each render gets its own snapshot and setting it asks React to render again.
On the first render, state count is a snapshot of 0, and countRef points to a box holding 0.
Try it. The left button only updates a ref, so the number on screen does not move until something else causes a render.
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.
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.
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.
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>;
}Refs vs state
useState | useRef | |
|---|---|---|
| Changing it re-renders | Yes | No |
| Value during a render | A fixed snapshot | Whatever was last written |
| How you update it | setX(next) | ref.current = next |
| Read it during render? | Yes, that is the point | Avoid (except lazy initialization) |
| Good for | Anything shown on screen | DOM 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.
Ref or state?
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.
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
}}
/><p>{renderCountRef.current}</p> and increments the ref in the component body to show a render counter. What is the problem?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:
- After React commits the element, it calls your callback with the DOM node.
- If the callback returned a function, React keeps it as the cleanup.
- When the node is removed, React calls the cleanup. It does not call your callback with
nullany more, as it did before React 19 (it still does for callbacks that return nothing). - 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.
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; }}.
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>
);
}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.
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.
React writes the tooltip with a guessed position. Nothing is on screen yet.
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.
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?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 anIntersectionObserverorResizeObserverto every child.getClientRects(),scrollIntoView(),compareDocumentPosition(): measure, scroll to, and order the group.
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 onceThis 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 each job to the tool that fits it best.
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}.
- ref
- A
{ current }object fromuseRefthat persists across renders. Changingcurrentdoes not re-render. - DOM ref
- A ref passed to a JSX element's
refattribute. React setscurrentto the DOM node after commit and back tonullon 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
reflike any other prop, replacingforwardRef. - ref callback cleanup
- In React 19, a function passed to
refcan 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.