Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 132 ยท Performance

Large Lists and Virtualization

Render 10,000 rows without freezing the page. Build a windowed list by hand, learn when to paginate instead, and see how react-window, TanStack Virtual and content-visibility fit in.

React can render a list of 100 items without effort and a list of 1,000 without much trouble. At 10,000 or 100,000, the story changes. The problem is rarely React's own work. It is the browser: each item becomes DOM nodes, and every node costs memory, style calculation and layout. A table with 10,000 rows and ten cells each is 100,000 elements, and the page becomes slow to load, slow to scroll and slow to update.

No amount of memo fixes that, because memo only skips rendering; the nodes still exist. The real fix is to not create most of them. This lesson shows the idea of virtualization (windowing) by building it by hand, compares it with pagination and infinite scroll, and then tells you which libraries to use in real projects.

The cost of many rows

First, see the numbers. This example renders as many rows as you choose and reports how many <li> elements are really in the document.

Counting DOM nodes

Press "10000 rows": the status line reports 10000 elements, while the user sees about six of them at a time in the 160 px box. The other 9,994 are pure cost. Virtualization asks the obvious question: why build what nobody can see?

The idea: render only the visible window

A virtualized list keeps a tall empty container (so the scrollbar looks right), and renders only the rows that intersect the viewport, plus a few spare ones above and below (the overscan) to avoid blank flashes while scrolling. As the user scrolls, the window moves and the rows swap.

For rows of a fixed height the math is small:

  • scrollTop is how far the viewport has scrolled.
  • First visible row: Math.floor(scrollTop / rowHeight).
  • Number of rows that fit: Math.ceil(viewportHeight / rowHeight).
  • Total height of the scrollable area: itemCount * rowHeight.
  • Each rendered row is positioned absolutely at top = index * rowHeight.

The only state you need is scrollTop, updated from the scroll event.

A virtualized list written by hand

On the first render the console prints rendering rows 0 to 10 (11 rows): rows 0 to 6 fill the 224 px viewport and rows 7 to 10 are the extra rows below it (nothing exists above the top yet). Scroll the box and the log follows, with at most 15 rows in the DOM no matter how far you go. Jump to the middle (drag the scrollbar) and it renders rows around the new position only. A native list of 100,000 items would take seconds to build; this one costs about the same as a list of fifteen.

How it works, step by step, for a scroll to 1,000 px: firstIndex = floor(1000 / 32) - 3 = 28, lastIndex = ceil((1000 + 224) / 32) + 3 = 42. React renders 15 rows with keys 28 to 42. Row 27 and everything above it is not in the DOM; as the user keeps scrolling down, rows leaving at the top are unmounted and new rows mount at the bottom. Because keys are item indexes, rows that stay in the window keep their DOM nodes (see Reconciliation and Keys).

Setting state on every scroll event can render many times per second. That is fine here because each render is tiny (a dozen rows), and React batches updates. For heavier rows, throttle with requestAnimationFrame or keep the row components memoized (memo). Also remember onScroll in React is passive, so you cannot call preventDefault in it.

Checking the window logic

The two helpers that matter are easy to get off by one, so treat them as plain functions you can test in isolation. A quick console check of the math from above:

The window math

The three lines read top: rows 0 to 10 (11), at 1000px: rows 28 to 42 (15) and bottom of 1000 rows: rows 996 to 999 (4). The clamps with Math.max and Math.min keep the window inside the data at both ends.

Variable heights, measuring and horizontal grids

The by-hand version assumes every row is exactly 32 px. Real lists often have rows of different heights (chat messages, wrapped text, expandable cards). Then you cannot compute a row's position with a multiplication. Options:

  • Estimate and measure. Give each row an estimated height, render, measure the real height with a ref (getBoundingClientRect() or ResizeObserver), store it, and recompute offsets with a running sum. Scrollbar size shifts slightly as estimates get corrected.
  • Make rows fixed on purpose. Truncate text with CSS ellipsis and put detail in an expandable panel.
  • Use a library. This is where libraries repay their cost.

Grids (rows and columns), sticky headers, keyboard navigation, scroll-to-index, scroll anchoring and accessibility semantics (role="list", aria-rowcount, aria-setsize) are each another few hundred lines, which is why you rarely write this yourself.

Libraries (read-only)

The following needs npm packages, which our editor does not have, so these snippets are shown, not run.

JSX
// react-window: small and focused, fixed or variable sizes
import { FixedSizeList } from 'react-window';

function Names({ names }) {
  return (
    <FixedSizeList height={320} width="100%" itemCount={names.length} itemSize={32}>
      {({ index, style }) => <div style={style}>{names[index]}</div>}
    </FixedSizeList>
  );
}
JSX
// TanStack Virtual: headless hook, you render the markup yourself
import { useVirtualizer } from '@tanstack/react-virtual';

function Names({ names }) {
  const parentRef = useRef(null);
  const virtualizer = useVirtualizer({
    count: names.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 32,
    overscan: 5,
  });

  return (
    <div ref={parentRef} style={{ height: 320, overflow: 'auto' }}>
      <div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
        {virtualizer.getVirtualItems().map((item) => (
          <div key={item.key} style={{ position: 'absolute', top: 0, transform: `translateY(${item.start}px)`, height: item.size }}>
            {names[item.index]}
          </div>
        ))}
      </div>
    </div>
  );
}

Both do exactly what the hand-written list does, with measurement, grids and scroll helpers added. react-window is the lighter choice; TanStack Virtual gives you more control and also supports variable sizes, horizontal lists and window scrolling. Treat the exact API names as a snapshot: check the library's documentation for the current version.

Trade-offs of virtualization

  • Browser find (Ctrl+F) cannot see rows that are not in the DOM.
  • Accessibility: screen readers only know about rendered rows unless you provide aria-rowcount/aria-setsize and position info.
  • State inside rows is lost when a row scrolls out and is unmounted. Keep important state (selection, drafts, expanded flags) in the parent or a store, keyed by item id.
  • SEO and printing: content that is not rendered is not indexed or printed.
  • Extra complexity in styling, focus management and tests.

Pagination, infinite scroll or virtualization?

Approach Good for Watch out for
Pagination (pages of 20 to 100) Search results, admin tables, anything people link to Extra clicks; needs a count and stable sorting
Infinite scroll (append more as you near the end) Feeds and timelines Hard to reach the footer; the DOM keeps growing, so combine with virtualization for very long sessions
Virtualization Big data already on the client: logs, spreadsheets, long selects Complexity, find-in-page

Often the best performance fix is the least clever one: return less data. A server that sends 50 rows per page beats any client trick.

Here is the smallest pagination, a slice of the data plus two buttons. The "server" is simulated with an array.

Pagination

Click Next ten times: the label reads Page 10 of 10, the list shows Product 91 to Product 95 (five items) and Next is disabled.

Infinite scroll in a few lines

Infinite scroll appends the next chunk when the user nears the bottom. Combine onScroll with a loading guard. This version simulates a server with a short delay and caps at 60 items.

Infinite scroll with a simulated server

Scroll to the bottom of the box. The header briefly shows (loading...) and then changes from Loaded 20 of 60 to Loaded 40 of 60; scroll to the bottom again for Loaded 60 of 60 and the line End of list. The loading flag prevents a second request while the first is running, which would otherwise duplicate chunks when scroll events fire repeatedly. Production code usually uses an IntersectionObserver sentinel instead of the scroll math, plus error handling and cancellation (see useEffect cleanup).

A CSS option: content-visibility

Sometimes the cheapest speed-up is not JavaScript at all. The CSS property content-visibility: auto tells the browser to skip layout and painting of an element while it is off-screen. Combined with contain-intrinsic-size, which gives the skipped element an estimated size so the scrollbar stays steady, long pages of independent sections become much cheaper.

content-visibility on long sections

All 200 sections stay in the DOM (so find-in-page and accessibility keep working), but the browser only lays out and paints the visible ones. It cuts rendering cost in the browser, not React's cost of creating elements, so it suits content with heavy layout rather than 100,000 trivial rows. Support is good in modern browsers, but check a compatibility table for your audience.

Pitfalls professionals know

  • Do not virtualize prematurely. Under about 500 simple rows, a normal list is fine. Measure first with the Profiler.
  • Stable keys by item id, not index, when the data can change (sorting, filtering).
  • Fixed row height is the biggest simplifier; design for it where you can.
  • Put the state outside the rows so scrolling does not lose edits.
  • Debounce filtering of huge arrays or use transitions so typing stays responsive while the list recomputes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does memo not solve the problem of rendering 100,000 rows?

    The cost is mostly the browser handling a huge DOM. Virtualization attacks that by creating only the visible rows.
  2. 2. In a fixed-height virtualized list, which expression gives the index of the first visible row (before overscan)?

    Dividing the scroll offset by the row height tells you how many rows have scrolled past the top edge.
  3. 3. What is the purpose of overscan?

    Rows just outside the viewport are rendered ahead of time so they are ready when scrolled into view.
  4. 4. Which is a downside of virtualization?

    Unrendered rows do not exist in the DOM. Keep important state outside the rows and consider accessibility attributes.
  5. 5. What does content-visibility: auto do?

    The elements stay in the document, but the browser avoids rendering work for those not near the viewport.

Summary

  • Big lists are slow mainly because of the browser's DOM cost, not because of React renders; memo does not remove nodes.
  • Virtualization renders only the rows in (and near) the viewport inside a tall spacer, using scrollTop and a fixed row height.
  • Variable heights need measuring; for grids and production use, choose react-window or TanStack Virtual.
  • Pagination and infinite scroll reduce data instead; returning less from the server is often the best fix.
  • content-visibility: auto is a CSS-only way to skip off-screen layout and paint.
  • Mind the trade-offs: find-in-page, accessibility and row-local state.

Next: Code Splitting with lazy and Suspense