Sub topic 13
Refs for lists of elements
This chapter assumes you know useRef, how to attach a ref to a single DOM element, and the basics of callback refs. Here you will handle the case where you render many elements and need a handle on each one.
Why a single ref is not enough
useRef holds one value. A list can have any number of items, so you cannot call useRef once per item. Hooks must not be called inside loops, callbacks, or map.
Passing the same ref to every item doesn't work either. Each item overwrites ref.current, so you end up with only the last element.
The usual fix is one ref that holds a Map. The keys are item IDs and the values are DOM nodes. A callback ref on each item adds its node to the map and removes it again.
A gallery with scroll buttons
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 code has three parts:
nodesRefis a single ref whosecurrentvalue is theMap.getMapcreates theMapthe first time it is needed. This is the lazy initialization pattern. It is safe to writeref.currenthere because the code only runs after React has attached refs, or in an event handler, and never during the render itself.- The
refon each<li>is a function. React calls it with the DOM node when the element is added. It calls it withnullwhen the element is removed.
What React does with the callback
The inline arrow function is a new function on every render. React treats a new callback as a different ref. It calls the old one with null, then calls the new one with the node. This is harmless for a Map, because the entry is deleted and added again in the same commit. It is also why the null branch is required. Without it, removed items would stay in the map.
Common mistakes
- Calling
useRefinmap. This breaks the rules of hooks. The number of hooks would change whenever the list length changes. - Using the array index as the key. If the list is reordered, the same index points at a different item. Use a stable ID for both the React
keyand theMapkey. - Reading the map during render. Nodes don't exist until the commit. Read them in event handlers or effects.
- Forgetting the
nullcase. The map would hold references to detached DOM nodes. That leaks memory and can makescrollIntoViewrun on nodes that are no longer in the page.
Exercise
In the Gallery, the <li> callback ref is called with null when an item is removed. What would go wrong if the else branch that calls map.delete(item.id) were left out, and what is a safer key than the array index?
Show answer
Removed items would stay in the Map, so it would keep references to DOM nodes that are no longer on the page. That leaks memory, and scrollTo could call scrollIntoView on a detached node and do nothing visible. A stable item ID, such as item.id, is safer than the index because it keeps pointing at the same item when the list is reordered or filtered.