Course contentsShow
← React
Lesson 721 of 2,39619. useRefFree lesson

Multiple Refs in Lists

Managing collections of refs using useRef with a Map or array for dynamic lists.

Multiple Refs in Lists

What you'll learn: How to manage multiple refs for dynamically rendered list items using arrays or Maps.

The Challenge with Lists

When you render a list with .map(), each item might need its own ref — but you can't call useRef() in a loop. Hooks must be called at the top level, once per render. So how do you attach refs to 10, 100, or an unknown number of list items?

The Solution: Ref Callbacks with a Collection

Instead of creating separate refs, you store all your element references in a single data structure — either an array or a Map. You use the ref callback pattern (lesson 720) to populate this collection as each element mounts.

Using a Map (Best for Dynamic Lists)

function ItemList({ items }) {
  const itemRefs = useRef(new Map());

  return (
    <ul>
      {items.map(item => (
        <li
          key={item.id}
          ref={(node) => {
            if (node) {
              itemRefs.current.set(item.id, node);
            } else {
              itemRefs.current.delete(item.id);
            }
          }}
        >
          {item.name}
        </li>
      ))}
    </ul>
  );
}

The ref callback runs for each element. When mounting, node exists, so you store it in the Map. When unmounting, node is null, so you clean up.

Using the Refs

function focusItem(id) {
  itemRefs.current.get(id)?.focus();
}

You retrieve individual elements by their key from the Map.

Why a Map?

A Map lets you look up refs by ID efficiently, which is perfect when items can be added, removed, or reordered. Arrays work too but require careful index management.

Key Takeaway: For lists needing refs, use a single useRef(new Map()) combined with ref callbacks to dynamically collect and manage element references as items mount and unmount.