Trivia Questions1 min readPremium

List Virtualization (Windowing)

Rendering 10,000 rows creates 10,000+ DOM nodes. Layout, style recalculation, memory, and the initial render all scale with that number, so scrolling stutters. Virtualization (also called windowing) renders only the rows that are visible, plus a small buffer. List virtualization is what libraries such as react-window implement for you.

1. The Idea Behind List Virtualization

  • A scroll container with a fixed height.
  • An inner spacer element whose height equals the total height of all rows, so the scrollbar looks correct.
  • Only the visible slice of rows is rendered, absolutely positioned (or translated) to where it would be in the full list.

2. The math (fixed row height)

const totalHeight = itemCount * rowHeight;
const startIndex  = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
const endIndex    = Math.min(
  itemCount - 1,
  Math.ceil((scrollTop + viewportHeight) / rowHeight) + overscan,
);
// render items[startIndex..endIndex], each at top = index * rowHeight

Overscan renders a few extra rows above and below the viewport so fast scrolling does not reveal blank space.

3. A minimal implementation

function VirtualList({ items, rowHeight, height, overscan = 5, renderRow }) {
  const [scrollTop, setScrollTop] = useState(0);
  const start = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
  const end = Math.min(items.length, Math.ceil((scrollTop + height) / rowHeight) + overscan);

  return (
    <div style={{ height, overflowY: 'auto' }} onScroll={e => setScrollTop(e.currentTarget.scrollTop)}>
      <div style={{ height: items.length * rowHeight, position: 'relative' }}>
        {items.slice(start, end).map((item, i) => (
          <div key={item.id} style={{ position: 'absolute', top: (start + i) * rowHeight, height: rowHeight, width: '100%' }}>
            {renderRow(item)}
          </div>
        ))}
      </div>
    </div>
  );
}

4. Trade-offs

  • Find-in-page (Ctrl+F) cannot find rows that are not in the DOM.
  • Accessibility: screen readers only see rendered rows; set aria-rowcount/aria-rowindex (or aria-setsize/aria-posinset) so the full size is announced.
  • Row state is lost when a row scrolls out and unmounts; keep it in the parent or store, keyed by id.
  • SEO: off-screen content is not in the server HTML.
  • Libraries: react-window, react-virtuoso, TanStack Virtual; React Native’s FlatList virtualizes by default.
  • CSS content-visibility: auto lets the browser skip rendering off-screen content while keeping it in the DOM. It is a lighter option for long documents, but it does not reduce the DOM node count.

When to reach for it

Use virtualization when lists reach the high hundreds or thousands of non-trivial rows, or when profiling shows render and layout time growing with list length. For short lists, plain rendering is simpler.