Frontend Case Studies

Topic F6

Virtualizing long lists

Creating only the visible rows: a sliding window for lists of thousands.

9 min · intermediate

Watch: of 1,000 rows, only the ones visible on screen are actually created. As you scroll, the window moves along.

… 980 moreviewport1234567891011121314151617181920
  • moving now
Step 1 of 5

A 1,000-row list. The screen fits only 5, but all 1,000 are created as DOM elements.

The user only sees a few rows at a time. Virtualization only creates those rows.

Why lots of elements are slow

Every DOM element uses memory and has to be styled, laid out and painted. A 10,000-row list with 5 elements per row is 50,000 elements. The first render can take seconds, every small change triggers expensive relayout, and scrolling stutters on cheap phones. Google suggests keeping a page under roughly 1,400 DOM elements.

How it works

  1. Know every row's height (or measure it the first time it shows).
  2. From the scroll position, work out the first visible row: Math.floor(scrollTop / rowHeight).
  3. Render only from that row to the last one that fits on screen, plus a few spare rows (overscan) so fast scrolling doesn't flash empty gaps.
  4. Put those rows inside a container as tall as the whole list, shifted with transform, so the scrollbar stays right.
Code, for programmersWith TanStack Virtual
import { useVirtualizer } from "@tanstack/react-virtual";

function BigList({ rows }) {
  const parentRef = useRef(null);
  const v = useVirtualizer({
    count: rows.length,                 // 10,000 rows
    getScrollElement: () => parentRef.current,
    estimateSize: () => 36,             // px per row
    overscan: 5,
  });
  return (
    <div ref={parentRef} style={{ height: 400, overflow: "auto" }}>
      <div style={{ height: v.getTotalSize(), position: "relative" }}>
        {v.getVirtualItems().map((item) => (
          <div key={item.key} style={{ position: "absolute", top: 0, width: "100%",
                                       transform: `translateY(${item.start}px)` }}>
            {rows[item.index].name}
          </div>
        ))}
      </div>
    </div>
  );
}

Quiz

  1. A 50,000-row list, 10 rows fit on screen, overscan 3. Roughly how many rows are in the DOM with virtualization?

  2. Why is the container made as tall as the whole list?

  3. What's a downside of virtualization?

0 of 3 answered.