Sub topic 10
Callback refs
This chapter assumes you know useRef with an object ref (ref={inputRef}), useState, and useEffect. An object ref works well when you have one element and know about it ahead of time. A callback ref covers the cases where you don't.
What a callback ref is
The ref attribute also accepts a function. React calls that function with the DOM node when the element is added to the page. It calls it again with null when the element is removed. This gives you a hook into the moment the node appears or disappears, which ref.current alone can't do.
Running code when an element appears
An object ref can't tell you when a conditionally rendered element shows up. A callback ref can.
import { useCallback, useState } from 'react';
export function Rename() {
const [editing, setEditing] = useState(false);
const focusOnMount = useCallback((node) => {
if (node) node.focus();
}, []);
return editing ? (
<input ref={focusOnMount} defaultValue="Untitled" />
) : (
<button onClick={() => setEditing(true)}>Rename</button>
);
}When you click the button, the input mounts and React calls focusOnMount with the node. The if (node) check handles the later call with null.
Keep the function stable
If you write the function inline, it is a new function on every render. React treats a changed ref as a reason to call the old function with null and the new one with the node. That is harmless for a cheap task. It is wasteful, or wrong, if the callback does real work such as measuring or subscribing.
Wrap the callback in useCallback with the right dependencies when it should only run on mount and unmount. An inline function is fine when you want it to run each render or when the work is trivial.
Cleanup functions in React 19
In React 19 a callback ref can return a cleanup function. React runs that function when the element is removed, and it no longer calls the ref with null in that case.
<div
ref={(node) => {
const observer = new ResizeObserver(() => {
console.log(node.getBoundingClientRect().width);
});
observer.observe(node);
return () => observer.disconnect();
}}
/>This keeps setup and teardown next to each other. On React 18 and earlier, do not return a function from a ref callback. Handle the null call instead.
Refs for many elements
A hook call can't happen inside a loop, so you can't call useRef once per list item. Instead, keep one ref that holds a Map from item ID to DOM node. Each item's callback ref adds or removes its own entry.
import { useRef } from 'react';
export function Gallery({ items }) {
const nodesRef = useRef(null);
function getMap() {
if (nodesRef.current === null) {
nodesRef.current = new Map();
}
return nodesRef.current;
}
function scrollTo(id) {
getMap().get(id)?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
return (
<>
<nav>
{items.map((item) => (
<button key={item.id} onClick={() => scrollTo(item.id)}>
{item.title}
</button>
))}
</nav>
<ul>
{items.map((item) => (
<li
key={item.id}
ref={(node) => {
const map = getMap();
if (node) {
map.set(item.id, node);
} else {
map.delete(item.id);
}
}}
>
{item.title}
</li>
))}
</ul>
</>
);
}The Map is created the first time getMap runs, so it is not rebuilt on every render. The inline callback is fine here. Between renders React calls it with null and then with the node, so each entry is deleted and set again with the same value.
Common mistakes
- Forgetting the
nullcase. The callback runs on unmount too, sonode.focus()without a check throws. - Reading
nodesRef.currentwhile rendering. The map is filled after React commits, so read it in event handlers or effects. - Returning a value from a callback ref on React 18. Early versions of React would ignore it, and newer ones treat it as a cleanup function.
Exercise
Why does a callback ref that is defined inline run twice on every re-render, and how do you stop that?
Show answer
Each render creates a new function, so React sees a changed ref. It calls the old function with null and the new function with the node. Wrap the callback in useCallback with a stable dependency list so the function identity stays the same.