Sub topic 13
Refs for lists of elements
This chapter assumes you know useRef for a single DOM node, useState, and how map renders lists with key. It covers how to hold a ref to each item of a list when you don't know how many items there will be.
Why one ref per item doesn't work
A single ref holds one value. A list can have any number of items, and that number changes at runtime. You might try to call useRef once per item inside map:
// Broken: hooks can't be called inside loops or callbacks
{items.map((item) => {
const ref = useRef(null);
return <li key={item.id} ref={ref}>{item.title}</li>;
})}This breaks the Rules of Hooks. React identifies hooks by the order in which a component calls them. If items changes length, the number of hook calls changes, and React can no longer match each call to its stored state.
Two other approaches are common:
- Give the parent one ref, then use
ref.current.querySelectorAll('li')to find the children. This works for simple cases, but it ties your code to the DOM structure and CSS selectors. - Keep a single ref that holds a collection (a
Map) of nodes, and fill it using callback refs. This is the approach this chapter develops.
The Map-in-a-ref pattern
A callback ref is a function you pass as the ref attribute. React calls it with the DOM node when the element is added to the screen. It calls it with null when the element is removed.
Combine this with one useRef that holds a Map from item id to DOM node:
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>
</>
);
}Each part has a job:
nodesRefis the single hook call. It lives for the life of the component.getMapcreates theMapthe first time anyone needs it. Writing toref.currentduring render is normally forbidden, but this one-time lazy initialization is the accepted exception. It is safe because the result doesn't depend on anything that changes between renders.- The callback ref adds the node to the map when it receives a node and deletes the entry when it receives
null. scrollToruns in an event handler, which is the right place to read refs.
The map is keyed by item.id, not by array index. If items are reordered or removed, an id still points to the same logical item. An index would point to a different one.
What happens during a render
The diagram shows when React calls your callback ref relative to the render and commit phases.
Refs are filled during the commit phase, after the render function has returned. Reading the map inside the component body would see stale or missing nodes. Read it in event handlers and effects.
Inline callbacks run on every render
In the example above, the ref function is created inline. A new function is a new value, so in React 18 and earlier React treats it as a changed ref on every render. It calls the old function with null, then the new function with the node. The map entry is deleted and re-added each time. The result is correct, but it does extra work.
React 19 lets a ref callback return a cleanup function. React then calls that cleanup instead of calling the callback with null:
<li
key={item.id}
ref={(node) => {
const map = getMap();
map.set(item.id, node);
return () => {
map.delete(item.id);
};
}}
>
{item.title}
</li>In React 19 the callback no longer receives null when a cleanup function is returned. Don't use this form on React 18, where a returned function is ignored and node can be null. Check your React version before choosing the form.
Acting on a newly added item
Suppose a user adds an item and you want to scroll to it at once. State updates are batched, so right after setItems(...) the new node doesn't exist yet. getMap().get(newId) returns undefined.
flushSync from react-dom forces React to update the DOM before the next line runs:
import { useRef, useState } from 'react';
import { flushSync } from 'react-dom';
let nextId = 3;
export function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Buy milk' },
{ id: 2, text: 'Write chapter' },
]);
const nodesRef = useRef(new Map());
function addTodo() {
const todo = { id: nextId++, text: `Task ${nextId - 1}` };
flushSync(() => {
setTodos((current) => [...current, todo]);
});
nodesRef.current.get(todo.id)?.scrollIntoView({ block: 'nearest' });
}
return (
<>
<button onClick={addTodo}>Add</button>
<ul style={{ height: 80, overflow: 'auto' }}>
{todos.map((todo) => (
<li
key={todo.id}
ref={(node) => {
if (node) nodesRef.current.set(todo.id, node);
else nodesRef.current.delete(todo.id);
}}
>
{todo.text}
</li>
))}
</ul>
</>
);
}Here useRef(new Map()) is acceptable because a Map is cheap. The tradeoff is that new Map() is evaluated on every render and thrown away, since React only uses the first value. For an expensive object, use the lazy getMap form from the first example.
Use flushSync sparingly. It skips React's batching and can hurt performance. An alternative with no flushSync is to store the id to scroll to in state, then scroll in an effect that runs after the commit.
Common mistakes with list refs
| Mistake | Symptom | Fix |
|---|---|---|
| Calling `useRef` inside `map` | Error about hook order, or broken state | Use one ref holding a `Map` |
| Using the array index as the Map key | Wrong element after reorder or delete | Key by a stable id |
| Reading the Map during render | Missing or stale nodes on the first render | Read it in handlers or effects |
| Forgetting to delete on `null` | Detached nodes stay in the Map (a memory leak) | Delete the entry in the `null` branch or in the cleanup |
| Not guarding against a missing entry | `Cannot read properties of undefined` | Use `get(id)?.method()` |
| Mixing the React 18 and 19 callback forms | Entry never deleted, or a `null` node is stored | Match the form to your React version |
A related gotcha concerns key. If a key changes, React treats the element as a new one. It unmounts the old element, so the callback receives null, and mounts a new one. The Map stays correct, but any DOM state on the old node (focus, scroll position, typed text) is lost.
Choosing an approach
- Use the Map-in-a-ref pattern when you need to reach any item by id from handlers or effects.
- Use a parent ref with
querySelectorAllwhen the list is rendered by code you don't control, or when you need all children at once and don't mind a selector. - Use plain state or props when the goal is to change what an item looks like. Highlighting an item belongs in state and CSS, not in DOM manipulation through a ref.
Exercise
A component renders items.map((item, index) => <li key={item.id} ref={(node) => { nodes.current[index] = node; }}>…</li>), where nodes is useRef([]). The user deletes the first item. Why is nodes.current[0] now a problem, and how would you change the code?
Show answer
In React 18, when the first item unmounts, its callback runs with null. That sets nodes.current[0] = null. The remaining items re-render at new indexes, and their callbacks write their nodes back into the array. Depending on call order, the array can contain a null hole, or nodes.current[index] can point to a node that no longer matches the item you expect. Indexes shift when items are removed, so they are an unreliable lookup key. Switch to a Map keyed by item.id. In the callback, call map.set(item.id, node) when node is not null, and map.delete(item.id) otherwise. Then look up nodes with map.get(id)?.….
Exercise
You call setItems([...items, newItem]) and on the next line run getMap().get(newItem.id).scrollIntoView(). It throws because the entry is undefined. Give two ways to fix it.
Show answer
React batches state updates, so the new <li> isn't in the DOM yet and its callback ref hasn't run. First fix: wrap the update in flushSync(() => setItems(...)) so the DOM updates before the next line, then scroll. Second fix: store the new id in state (or in a ref) and run the scroll inside a useEffect that depends on it, since effects run after the commit when the node is in the Map.