Skip to content
FrontDepth, Home

Browser & Performance

List virtualization

Why thousands of DOM nodes make a page slow and how windowing keeps lists fast — from the fixed-height math and infinite scroll to measured heights, scroll anchoring, accessibility costs and the alternatives.

MiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

This topic starts at Middle level.

MiddleConcept

Why thousands of DOM nodes are slow

A row on the screen costs far more than the data behind it. Filtering 10,000 objects in JavaScript takes a few milliseconds; turning them into 10,000 table rows does not. Every element pays in several stages, and the costs grow with the number of rows, not with what the user can see:

  1. Creating it. React calls every row component, creates its elements and fibers, and then the DOM nodes.
  2. Style. The browser matches selectors and computes styles for each element.
  3. . Every box gets a size and position. With the default table-layout: auto, column widths depend on the content of every cell, so a table lays out all its rows to size its columns.
  4. Memory. DOM nodes, computed styles, layout objects and React's fibers all stay alive while the rows exist.
  5. Every update. When the list's parent re-renders — say, on each letter typed into a search box — React calls every row component again and compares every row's output before the browser can paint the next frame.

Paint is the exception: browsers mostly paint what is near the viewport, so off-screen rows cost little , but they still pay every other cost above.

JSX
function TransactionsTable({ transactions }) {
  return (
    <table className="transactions">
      <tbody>
        {transactions.map((t) => (
          <tr key={t.id}>
            <td>{t.date}</td>
            <td>{t.merchant}</td>
            <td>{t.category}</td>
            <td>{t.card}</td>
            <td>{t.amount}</td>
            <td>{t.status}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

Picture a table of 10,000 transactions with six cells per row: 70,000 elements or more, created in one long task when the page opens and rendered again on every keystroke in its filter box — while the scroll area shows perhaps a dozen rows. With a few hundred test records nobody notices; with production data each interaction takes seconds, which is exactly what INP measures.

How to spot it

  • In the Performance panel, a long task on the dominated by scripting (React rendering the rows) plus "Recalculate style" and "Layout".
  • document.querySelectorAll("*").length in the console. Lighthouse warns when the body has more than about 800 nodes and reports an error above about 1,400 (since Lighthouse 13 this lives in the "Optimize DOM size" insight).
MiddleConcept

Windowing: render only what is visible

Windowing (also called virtualization) keeps the full data in memory but renders only the rows inside the viewport, plus a few extra rows above and below — the overscan. The DOM stays the same size whether the list has 300 items or 300,000.

The structure has three parts: a viewport with a fixed height and overflow-y: auto, a spacer as tall as the whole list so the scrollbar has the right size and range, and the window of rendered rows moved to where they belong:

HTML
<div class="viewport" style="height: 400px; overflow-y: auto">
  <div class="spacer" style="position: relative; height: 40000px">
    <div class="window" style="transform: translateY(880px)">
      <div class="row" style="height: 40px">Row 22</div>
      <div class="row" style="height: 40px">Row 23</div>
      <div class="row" style="height: 40px">Row 24</div>
    </div>
  </div>
</div>

(Libraries usually position each row absolutely instead; in a <table> you can keep the table semantics with an empty spacer row above and below the rendered rows.)

The math for fixed-height rows

When every row has the same height, positions are a multiplication and the visible range is a division:

JavaScript
function getRange({ scrollTop, viewportHeight, rowHeight, count, overscan }) {
  const first = Math.floor(scrollTop / rowHeight);
  const last = Math.ceil((scrollTop + viewportHeight) / rowHeight);
  const start = Math.max(0, first - overscan);
  const end = Math.min(count, last + overscan);
  return { start, end, offset: start * rowHeight, total: count * rowHeight };
}

getRange({ scrollTop: 1010, viewportHeight: 400, rowHeight: 40, count: 1000, overscan: 3 });
// { start: 22, end: 39, offset: 880, total: 40000 }
  • first is the row cut by the top edge, last is one past the row cut by the bottom edge, so end is exclusive and maps straight to items.slice(start, end).
  • At scrollTop 1010, rows 25–35 are visible; with overscan 3 the window holds rows 22–38: 17 rows instead of 1,000.
  • Clamp both ends. Overscan must not go below 0 or past count. And when a search shortens the list, the old scrollTop can lie far below the new end: clamp scrollTop to total - viewportHeight first, or the window is empty while a huge spacer keeps the page blank.

Choosing the overscan

Scrolling usually runs on the compositor, ahead of the main thread, so a fast fling can reach rows that are not rendered yet and show blank space for a frame or two. A larger overscan hides that; a smaller one keeps each render cheaper. A few rows to a screenful is common.

MiddleFramework

Windowing in React and with libraries

In React the hand-written version is a component that keeps scrollTop and the viewport height in state, computes the range during render, and renders items.slice(start, end). Scrolling re-renders only that component and its 20–30 rows. Three details matter:

  • Key rows by item id, not by the position in the slice. With ids, React keeps the rows that stay in the window and mounts only the ones that enter; with slice indexes every row's state and DOM would be reused for a different item.
  • Update state only when the range changes. scroll fires many times per second; storing the range (or rounding scrollTop to whole rows) avoids re-rendering on every pixel.
  • Measure the viewport in useLayoutEffect (and with a ResizeObserver when it can resize), so the first paint already shows the right rows.

useDeferredValue or memo alone do not shrink the DOM: typing may feel smoother, but every row still exists, and the first render still creates all of them.

TanStack Virtual

In production code, use a maintained library. TanStack Virtual is headless: it computes ranges and offsets and renders no markup of its own.

JSX
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";

function TransactionList({ transactions }) {
  const scrollRef = useRef(null);
  const virtualizer = useVirtualizer({
    count: transactions.length,
    getScrollElement: () => scrollRef.current,
    estimateSize: () => 40,
    overscan: 8,
    getItemKey: (index) => transactions[index].id,
  });

  return (
    <div ref={scrollRef} className="viewport">
      <div style={{ position: "relative", height: virtualizer.getTotalSize() }}>
        {virtualizer.getVirtualItems().map((row) => (
          <TransactionRow
            key={row.key}
            transaction={transactions[row.index]}
            style={{
              position: "absolute",
              top: 0,
              width: "100%",
              height: row.size,
              transform: `translateY(${row.start}px)`,
            }}
          />
        ))}
      </div>
    </div>
  );
}

Each virtual item has index, key, start, size and end. The default overscan is 1 and the default key is the index, so pass getItemKey. useWindowVirtualizer does the same for a list that scrolls with the page, and scrollToIndex() jumps to an item.

react-window (2.x) gives you components instead: List with rowComponent, rowCount, rowHeight and rowProps, a Grid for two dimensions, and useDynamicRowHeight for rows that cannot be sized ahead of time. Pick by need: TanStack when you want full control over markup (tables, masonry, sticky rows), react-window when a ready component fits.

MiddleExample

Infinite scroll with IntersectionObserver

Infinite scroll loads the next page when the user gets close to the end. Don't listen to scroll and compare scrollTop with scrollHeight on every event: that reads layout many times per second on the main thread. Put an empty sentinel element after the last item and let an IntersectionObserver tell you when it comes near the viewport. It is Baseline widely available (since March 2019).

JSX
import { useEffect, useRef } from "react";

function useLoadMore(loadMore, enabled) {
  const sentinelRef = useRef(null);

  useEffect(() => {
    if (!enabled) return;
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) loadMore();
      },
      { rootMargin: "0px 0px 800px 0px" },
    );
    observer.observe(sentinelRef.current);
    return () => observer.disconnect();
  }, [loadMore, enabled]);

  return sentinelRef;
}

function Feed({ posts, hasNextPage, isFetching, fetchNextPage }) {
  const sentinelRef = useLoadMore(fetchNextPage, hasNextPage && !isFetching);
  return (
    <div role="feed" aria-busy={isFetching} aria-label="News">
      {posts.map((post, i) => (
        <Post key={post.id} post={post} posInSet={i + 1} />
      ))}
      <div ref={sentinelRef} />
    </div>
  );
}
  • rootMargin: "0px 0px 800px 0px" grows the root by 800 px at the bottom, so the next page starts loading well before the end. If the list scrolls inside its own container, pass that element as root.
  • The observer is off while a page is loading, so the same page is never requested twice. When it is re-created, observe() delivers a first callback with the current state: if the sentinel is still near, the next page loads too, and a short first page fills the screen by itself.
  • Keep an error state and a visible "Load more" button as a fallback, and remember that a footer below an infinite list is hard to reach.
  • The ARIA feed pattern: role="feed", each post an article with aria-posinset and aria-setsize (-1 when the total is unknown), and aria-busy="true" while loading. Per the APG, Page Down and Page Up move focus between articles.

Infinite scroll is not windowing

Every page adds posts to the DOM, so a long session ends up with thousands of nodes again. Combine the two: virtualize the loaded posts, and trigger the next page from the range (when the last rendered index comes within a few items of count), because in a virtualized list the end of the DOM is not the end of the list.

SeniorWeb platform

Variable heights: estimate, measure, correct

Real rows rarely have one height: posts have images, text wraps differently on each screen, a row expands. Then the offset of row i is no longer i * rowHeight but the sum of all sizes before it.

Prefix sums and binary search

Keep offsets[i] = the start of row i (offsets[0] = 0, offsets[i + 1] = offsets[i] + size[i]). The total height is offsets[count], and the first visible row is found by a binary search for the largest i with offsets[i] <= scrollTop — O(log n) per scroll instead of walking the list. When one size changes, every later offset changes, so libraries update offsets lazily from the first changed index.

Estimate, then measure

Sizes are unknown until a row is rendered, so a virtualizer:

  1. Estimates a size for every unmeasured row (TanStack's estimateSize; its docs recommend estimating the largest likely size when measuring dynamically).
  2. Renders the window, then measures the rendered rows. TanStack's measureElement ref and react-window's useDynamicRowHeight use a ResizeObserver, which also catches later changes such as an image finishing loading.
  3. Caches the measured size by key, not by index, so sorting or filtering keeps the measurements, and recomputes the offsets.

Anchoring when sizes change

If a row above the viewport turns out 20 px shorter than estimated, everything below it moves up 20 px and the content under the user's eyes jumps. The fix is to shift scrollTop by the same delta before the frame is painted:

JavaScript
const measured = new Map();

const observer = new ResizeObserver((entries) => {
  let shift = 0;
  for (const entry of entries) {
    const key = entry.target.dataset.key;
    const size = entry.borderBoxSize[0].blockSize;
    const old = measured.get(key) ?? ESTIMATE;
    if (size === old) continue;
    measured.set(key, size);
    if (startOf(key) < viewport.scrollTop) shift += size - old;
  }
  if (shift !== 0) viewport.scrollTop += shift;
  scheduleRender();
});

Here startOf reads a row's offset from the prefix sums and every rendered row is observed with observer.observe(row). Resize observations are delivered before paint, so the correction lands in the same frame. TanStack Virtual does this for you; by default it applies the correction only when the user is not scrolling backward, and shouldAdjustScrollPositionOnItemSizeChange lets you change that rule.

Pitfalls

  • Measuring with getBoundingClientRect() in a loop that also writes styles causes .
  • A callback that resizes what it observes triggers "ResizeObserver loop completed with undelivered notifications": the rest waits for the next frame and the layout flickers.
  • The scrollbar thumb changes size as estimates are replaced; a good estimate keeps that small.
SeniorWeb platform

Keeping the scroll position: restoration and prepending

Two situations break the user's place in a long list: coming back to it, and new items appearing above what they are reading.

Restoring after navigation

The browser restores the document's scroll position on back and forward (history.scrollRestoration is "auto" by default). A virtualized list often defeats that: it scrolls inside its own container, its data arrives asynchronously, and with estimated heights it is not tall enough yet when the browser restores.

  • Save an anchor, not pixels: the key of the first visible item and how far the viewport top is inside it. A pixel offset is only valid for the same estimates and measurements.
  • Store it per history entry (in history.state or a map keyed by the entry), restore with scrollToIndex() and then add the offset.
  • Keep the data cached so the same items exist when the user returns, and set history.scrollRestoration = "manual" if your code takes over.

Prepending items

A chat loading older messages, or a feed inserting "12 new posts" at the top, adds height above the viewport, so the content being read moves down. In normal flow, browsers do scroll anchoring: they pick an anchor element in view and adjust the scroll position when content above it changes. It is on by default, and overflow-anchor: none opts out; MDN lists it as Baseline 2026 (Chrome 56, Firefox 66, Safari 27).

A virtualizer positions rows itself, so it corrects itself: add the height of the inserted items to scrollTop before the browser paints. In React, measure before the update and correct in useLayoutEffect:

JSX
const heightBefore = useRef(0);

async function loadOlder() {
  const older = await fetchOlderMessages(messages[0].id);
  heightBefore.current = viewportRef.current.scrollHeight;
  setMessages((list) => [...older, ...list]);
}

useLayoutEffect(() => {
  const viewport = viewportRef.current;
  if (heightBefore.current === 0) return;
  viewport.scrollTop += viewport.scrollHeight - heightBefore.current;
  heightBefore.current = 0;
}, [messages]);
  • If you correct by hand in a non-virtualized scroller, set overflow-anchor: none on it, or the browser and your code both correct and the list jumps the other way.
  • Keys must be stable ids: that is how a virtualizer tells a prepend from an append. TanStack Virtual has anchorTo: "end" for chats, logs and reverse feeds, and followOnAppend follows new items only when the user was already at the end — someone reading history is not pulled down.
SeniorPitfalls

What windowing costs: find-in-page, screen readers, focus

Windowing removes rows from the DOM, and everything that works on the DOM loses them too. These costs are why windowing is a trade-off, not a free speed-up.

Find-in-page

Ctrl+F / Cmd+F finds only rendered rows. Give users a search over the data itself (a search box that filters the full array) and keep it easy to find. content-visibility: auto is the opposite trade: skipped content stays searchable.

Screen readers

Assistive technology reads the accessibility tree, built from the DOM, so it sees about thirty rows of a 10,000-row table. Tell it the real size:

HTML
<table aria-rowcount="5001">
  <thead>
    <tr aria-rowindex="1">
      <th scope="col">Date</th>
      <th scope="col">Merchant</th>
    </tr>
  </thead>
  <tbody>
    <tr aria-hidden="true" style="height: 880px"></tr>
    <tr aria-rowindex="24">
      <td>2026-11-02</td>
      <td><a href="#/transactions/t-4023">Coffee Corner</a></td>
    </tr>
    <tr aria-rowindex="25">
      <td>2026-11-02</td>
      <td><a href="#/transactions/t-4024">City Books</a></td>
    </tr>
  </tbody>
</table>
  • aria-rowcount on the table/grid is the number of rows in the full table, header included; -1 means unknown.
  • aria-rowindex on each rendered row is its position in the full table, starting at 1. Here 22 rows are skipped (880 px of spacer at 40 px a row), so the first data row rendered is row 24 after the header.
  • For lists, options and feed articles use aria-setsize and aria-posinset on every item.
  • Hide spacer elements with aria-hidden="true".

Keyboard focus

A user tabs to a link in row 40 and then scrolls with the wheel. Row 40 leaves the window and unmounts, the focused element is gone, and focus falls back to <body>: the next Tab starts again from the top of the page. Fixes:

  • Keep the focused row rendered even outside the range (TanStack's rangeExtractor can add its index).
  • Or use the grid pattern: one tab stop for the table, arrow keys move the active row, and the code scrolls that row into view (scrollToIndex) before focusing it.

Other things that only see the DOM

In-page links to #order-123, printing, crawlers and tests: in jsdom there is no layout, the viewport height is 0, and a virtualized list may render nothing. Mock the size or test the range logic separately.

SeniorWeb platform

Alternatives: pagination, content-visibility, less data

Windowing is one answer to "too many nodes". Before reaching for it, ask what the user needs.

Load and render less

  • Filter, sort and search on the server. Downloading every record to filter it in the browser costs network, memory and parsing before rendering even starts; a server query with a limit sends what the user can look at.
  • Pagination. Small DOM, stable URLs (?page=3 or a cursor), find-in-page works on the page, and the back button lands where it should. The cost: no continuous scan through everything. Some products need one continuous list, and then pagination is not an option.
  • Cheaper rows. Fewer wrapper elements per row, simple selectors, table-layout: fixed so column widths do not depend on every cell.

content-visibility: auto

CSS
.post {
  content-visibility: auto;
  contain-intrinsic-size: auto 320px;
}

The browser skips style, layout and paint for the contents of elements that are not relevant to the user (off-screen), and renders them when they come near. Unlike windowing, the elements stay in the DOM and the accessibility tree: find-in-page, tab order and focus work as normal. contain-intrinsic-size: auto 320px gives skipped elements a placeholder size; with auto the browser remembers the real size once an element has been rendered, so the scrollbar stops jumping.

Support: content-visibility is Baseline 2024, newly available since September 2024 (Chrome 85, Firefox 125, Safari 18); contain-intrinsic-size is widely available.

What it does not remove: the DOM nodes are still created and kept in memory, and React still renders and compares every item on each update. It suits long documents and moderate feeds; it does not help a table whose tens of thousands of elements are re-rendered on every keystroke.

A rule of thumb

  • A few hundred simple rows: render them all, then measure.
  • A long page read from top to bottom: content-visibility: auto.
  • Thousands of rows, frequent updates, or a list that grows without end: windowing, with the accessibility work from the previous section.
  • Users navigate by position or share links to results: pagination.
  • In every case: do not download what you will not show.
SeniorInterview tips

Interview tips

A 30-second answer. "Every DOM node costs creation, style, layout and memory, and in React every row is also re-rendered on updates. Windowing renders only the rows in the viewport plus overscan inside a spacer as tall as the whole list, so the DOM stays constant. With fixed heights the range is floor(scrollTop / h) to ceil((scrollTop + height) / h); with variable heights you estimate, measure, cache by key and correct the scroll position."

Questions you are likely to get

  • Implement a virtual list. Write the range math with overscan and clamping, the spacer, and key rows by id. Mention measuring the viewport and updating state only when the range changes.
  • Rows have different heights. Prefix sums plus binary search, estimates, ResizeObserver measurements cached by key, and scroll correction for rows above the viewport.
  • Design an infinite feed. IntersectionObserver sentinel with a rootMargin, cursor pagination, virtualization for long sessions, role="feed", scroll restoration on back.
  • Why is this table slow? Measure first: Performance panel, DOM size, React Profiler. Show that you look at the rendering as well as at the data work.

Mistakes that cost points

  • Virtualizing a list of 50 items, or reaching for it before checking how much data you load.
  • Using the index in the visible slice as the key.
  • Forgetting the accessibility costs: find-in-page, aria-rowcount/aria-rowindex or aria-setsize/aria-posinset, focus on rows that unmount.
  • Believing content-visibility and windowing are the same: one keeps the DOM and skips rendering work, the other removes nodes.
  • Not clamping the range after the list shrinks.

Senior signal

Talk in trade-offs and numbers: the DOM budget you set, how you checked it in CI (element count after load, long tasks while typing), why you chose windowing over pagination for this product, and how you kept search, screen readers and the back button working.

Practise on the platform

The incident "The orders table freezes" (orders-unvirtualized), and the design problems "Infinite news feed" (infinite-feed) and "Analytics dashboard" (analytics-dashboard).

MiddleReview checklist

What to check when reviewing a virtualized list

Use this list when you review a virtualized list you did not write (a teammate's pull request, a library's example or an AI assistant's suggestion). Its bugs hide behind small test data and show up in production: rows with another item's state, a blank viewport, content that jumps, lost focus.

  • Are rows keyed by a stable item id, not by index? With index keys, a row's state and DOM pass to another item as the window moves. TanStack Virtual's default key is the index, so look for getItemKey.
  • Does the DOM really stay small? The range comes from the viewport's height, so the scroll container needs a fixed height and overflow-y: auto (or the list scrolls with the page via useWindowVirtualizer). Compare document.querySelectorAll("*").length at the top and far down: it should barely change.
  • Is the range clamped when the list gets shorter? Scroll to the bottom, then filter down to a few rows: a blank viewport means the old scrollTop was not clamped.
  • With variable heights, are rows measured by a ResizeObserver (TanStack's measureElement) and cached by key? getBoundingClientRect() in a loop that writes styles forces a per row. When a row above the viewport changes size, scrollTop must shift by that amount, or the content jumps.
  • Does keyboard focus survive scrolling? Tab to a link, scroll its row away with the wheel, press Tab. If focus restarts at the top of the page, the row was unmounted; keep it rendered (TanStack's rangeExtractor).
  • Can screen readers and search reach the whole list? Look for aria-rowcount and aria-rowindex (in lists, aria-setsize and aria-posinset) and aria-hidden spacers. Ctrl+F finds only rendered rows, so offer a search over the data.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    6 questions

Hands-on work that uses this topic.