Sub topic 10
Callback refs
This chapter assumes you know how useRef returns a { current } object and how to attach one to a DOM element with the ref attribute. You should also be comfortable with useState, useEffect, and closures.
What a callback ref is
The ref attribute on a DOM element accepts two kinds of values. One is the object that useRef returns. The other is a function, called a callback ref. React calls that function with the DOM node when the element is added to the screen. In React 18 and earlier, it calls the function again with null when the element is removed.
With an object ref, React writes to ref.current for you and you read it later. With a callback ref, you decide what happens at the moment the node appears. You can store it, measure it, or start something that depends on it.
import { useState } from 'react';
export function Greeting() {
const [text, setText] = useState('');
return (
<h1
ref={(node) => {
if (node !== null) {
setText(`I am a <${node.tagName.toLowerCase()}> element`);
}
}}
>
Hello
<small> ({text})</small>
</h1>
);
}The node !== null check matters in React 18 and earlier. React passes null on unmount, and code that reads node.tagName without the check throws.
When React calls the function
React attaches and detaches refs during the commit phase. This is the step after rendering, when React applies changes to the DOM. Two facts follow from that:
- Refs are not set while your component function runs. A callback ref is never called during rendering, so the node does not exist yet on the first render.
- By the time
useLayoutEffectanduseEffectrun, the refs have already been attached.
The next diagram shows what happens when the callback function changes between renders.
Why identity matters
Look at the sequence above. If you write the function inline, as in ref={(node) => { ... }}, you create a new function on every render. React sees a different function than last time. It calls the old one with null and the new one with the node, on every single render. This is usually harmless, but it is a problem in two situations:
- The callback does real work, such as measuring, subscribing, or setting state.
- The callback sets state in a way that triggers another render. This can form a loop.
To keep React from treating the callback as new, wrap it in useCallback. Give it a stable dependency list and React calls it only on mount and unmount.
import { useCallback, useState } from 'react';
export function MeasuredBox({ children }) {
const [height, setHeight] = useState(null);
const measuredRef = useCallback((node) => {
if (node !== null) {
setHeight(node.getBoundingClientRect().height);
}
}, []);
return (
<>
<div ref={measuredRef}>{children}</div>
{height !== null && <p>The box is {Math.round(height)}px tall.</p>}
</>
);
}This is the main reason to prefer a callback ref over useRef plus useEffect for this job. With an object ref, useEffect runs after the node exists, but it does not know when a node later appears or is swapped. For example, the element might be rendered conditionally after the first render. A callback ref is called exactly when the node attaches, however late that is.
The measurement above happens once. If the box changes size later, height stays stale. To track size changes, observe the node, as in the next section.
Cleanup functions in React 19
React 19 lets a callback ref return a cleanup function. When the element is removed, React calls the cleanup instead of calling your function with null. This keeps setup and teardown in one place, like an effect.
import { useCallback, useState } from 'react';
export function ResizableNote() {
const [width, setWidth] = useState(0);
const observeWidth = useCallback((node) => {
const observer = new ResizeObserver(([entry]) => {
setWidth(Math.round(entry.contentRect.width));
});
observer.observe(node);
return () => observer.disconnect();
}, []);
return (
<div
ref={observeWidth}
style={{ resize: 'horizontal', overflow: 'auto', border: '1px solid' }}
>
Width: {width}px
</div>
);
}Drag the bottom-right corner of the box to resize it, and the number updates. The observer is created when the node attaches and disconnected when it detaches. Because the function is returned and used as cleanup, React never calls it with null, so there is no null check.
React 19 also changes how arrow functions with implicit returns behave. In ref={(node) => (instance = node)}, the arrow returns the assigned value. React 19 would try to treat a returned non-function as a cleanup. TypeScript rejects this pattern for that reason. Use braces so the function returns nothing: ref={(node) => { instance = node; }}.
Callback ref or object ref
| Situation | Better choice |
|---|---|
| Read the node later in an event handler or effect | Object ref from `useRef` |
| Run code at the moment the node attaches | Callback ref |
| The node may appear after the first render | Callback ref |
| Store a node in state so a render can use it | Callback ref calling `setState` |
| Attach one ref per item in a list | Callback ref (see the chapter on lists) |
| Set up and tear down something tied to the node | Callback ref with cleanup (React 19) |
If you only need to call focus() from a click handler, useRef is simpler. Use a callback ref when the timing of attachment matters.
Putting a node into state
A callback ref can pass the node to useState. This gives you a value that triggers a render when it changes. An object ref cannot do this, because changing ref.current does not cause a render.
import { useState } from 'react';
export function Panel() {
const [panel, setPanel] = useState(null);
return (
<>
<div ref={setPanel} style={{ height: 80, overflow: 'auto' }}>
<p style={{ height: 400 }}>Scroll me</p>
</div>
<button onClick={() => panel?.scrollTo({ top: 0, behavior: 'smooth' })}>
Back to top
</button>
<p>{panel ? 'Panel mounted' : 'Panel not mounted yet'}</p>
</>
);
}setPanel is a stable function that React keeps the same between renders, so it works as a callback ref directly. React calls it with the node on mount and with null on unmount (React 18 and 19, since setPanel returns nothing). The second render happens right after the commit, so the UI can react to the node existing. Use this sparingly. Each node you store in state costs an extra render.
Combining two refs on one element
An element has only one ref attribute. If a component needs its own object ref and also has to honor a ref passed in from outside, write a small helper that fans the node out.
import { useRef } from 'react';
function mergeRefs(...refs) {
return (node) => {
for (const ref of refs) {
if (typeof ref === 'function') {
ref(node);
} else if (ref !== null && ref !== undefined) {
ref.current = node;
}
}
};
}
export function TextField({ forwardedRef }) {
const localRef = useRef(null);
return (
<input
ref={mergeRefs(localRef, forwardedRef)}
onFocus={() => console.log('focused', localRef.current.value)}
/>
);
}This helper creates a new function on each render, so React calls it with null and then the node every time. For a plain object ref, that is cheap and harmless. Wrap the helper call in useCallback or useMemo if the merged refs include a callback that does expensive work. The helper also ignores cleanup functions returned by the callbacks, so it is not suitable for React 19 refs that use cleanup.
Common mistakes
- Skipping the null check. In React 18, your function receives
nullon unmount. Guard every property access. - Writing the function inline when it does work. The function re-runs on every render. Move it into
useCallback. - Setting state to a new object each call. If the callback calls
setState({ ... })with a fresh object, and the function is inline, every render triggers another render. Store primitives, or memoize the callback. - Expecting the node during render. The callback has not run yet, so the node is unavailable. Read it from an effect or an event handler.
- Mixing cleanup styles. Do not write code that both returns a cleanup and expects a
nullcall. Pick one for your React version.
Exercise
A component renders <div ref={(node) => { if (node) setWidth(node.offsetWidth); }} />. Each render, the function is a new one. Explain what React calls on each update in React 18, why this can cause trouble, and how you would fix it.
Show answer
On every update, React calls the old function with null and then the new function with the node, because the function's identity changed. In the new call, setWidth runs again. If the width is the same number, React skips the extra render, so it may settle. But the function does needless work each time, and if it stored a new object each call it would loop. The fix is to wrap the function in useCallback with an empty dependency list, so React sees the same function between renders and calls it only on mount and unmount.
Exercise
You need to disconnect a ResizeObserver when its element is removed. Describe how to do this with a callback ref in React 19, and what changes in React 18.
Show answer
In React 19, create the observer inside a useCallback-wrapped callback ref, observe the node, and return a function that calls observer.disconnect(). React calls that cleanup when the element is removed and does not call the ref with null. In React 18, a returned function is ignored, so you must handle the null call yourself. Keep the observer in a variable outside the callback (for example in a useRef), disconnect it when node is null, and create it when node is not null.