What you'll learn: By the end of this lesson you will be able to decide whether a long list needs virtualization at all, work out with arithmetic which rows need a DOM node for a given scroll position, build a windowed list with a spacer, absolutely positioned rows and overscan, handle rows of different heights with prefix sums, and name what virtualization takes away (row state, find-in-page, simple accessibility) and how to give each back.
Think of a very long roll of paper pulled behind a small window. You never need the whole roll in front of you, only the part the window shows, plus a little on either side so nothing flashes blank when it moves. As the roll slides, you swap the visible strip. List virtualization (also called windowing) does that with rows: render only what the user can see, and make the scrollbar behave as if all of it were there.
The running example is the stock table of a grocery marketplace's merchant dashboard: ten thousand product rows, each with a name, a price and a stock field, in a scrolling panel. The previous lesson in this module, Pagination: Offset, Cursor and Infinite Scroll, ends with a list that only grows; this lesson is what you do when growth hurts.
The core idea
- The DOM costs per node, but the screen shows a fixed number of rows. web.dev says a larger DOM makes initial render more expensive and that updates which insert or change elements can cause costly layout, style and paint work. A viewport that shows fifteen rows needs about fifteen nodes, not ten thousand.
- The scrollbar is a promise, not a measurement. A spacer element as tall as the whole list keeps the scrollbar honest; the few rendered rows are positioned inside it at the offsets they would have had.
- Everything hangs on sizes. With equal heights the window is two divisions. With different heights you need cumulative offsets. With guessed heights you render the wrong rows.
Do you need it?
Virtualization has real costs, listed below, so try the cheaper options first. web.dev's guidance on virtualizing lists starts with measuring rendering and scrolling performance, and the same article warns that blank space can briefly flash as new rows are about to be displayed.
- Page the data (the previous lesson): a small DOM, a shareable position.
content-visibility: auto: MDN says it turns on layout, style and paint containment and skips rendering the contents of elements that are not relevant to the user, while the contents stay in the DOM and the accessibility tree and remain available to find-in-page. It saves rendering work; it does not remove nodes. web.dev adds that the browser needs a size hint (contain-intrinsic-size) or the scrollbar will shift.- Virtualize when there really are too many rows, the rows are heavy, and the above is not enough.
Figure 1. Choosing the cheapest fix
long list actually slow?"} A -->|"no"| N["Do nothing"] A -->|"yes"| B{"Can users work with
pages or a search?"} B -->|"yes"| P["Page or cap the list"] B -->|"no"| C{"Does content-visibility
auto fix it?"} C -->|"yes"| V1["Keep every row in the DOM,
skip off-screen rendering"] C -->|"no"| V["Virtualize: render a window"]
How to read this: measure first, because the cost of virtualization is paid whether or not the list was a problem. Each step trades something: paging changes the interface, content-visibility keeps the nodes, windowing removes them.
The window, for equal heights
Say every row is 40 px tall, the viewport is 600 px, and there are 10,000 rows (these figures are illustrative). At scroll position scrollTop, row i occupies the vertical range from i * 40 to (i + 1) * 40. So the first visible row is floor(scrollTop / 40), the last is ceil((scrollTop + 600) / 40) - 1, and the total height is 10000 * 40.
Illustration 1: the minimal example
const itemHeight = 40, viewport = 600, itemCount = 10000, overscan = 3;
function range(scrollTop) {
const first = Math.floor(scrollTop / itemHeight);
const last = Math.min(itemCount - 1, Math.ceil((scrollTop + viewport) / itemHeight) - 1);
return { first, last, start: Math.max(0, first - overscan), end: Math.min(itemCount, last + 1 + overscan) };
}
const r = range(400);
console.log(r);
console.log("rows in the DOM:", r.end - r.start, "of", itemCount);
console.log("spacer height:", itemCount * itemHeight);
console.log("row 12 top:", 12 * itemHeight);
Output, from running it in Node 26.13.1:
{ first: 10, last: 24, start: 7, end: 28 }
rows in the DOM: 21 of 10000
spacer height: 400000
row 12 top: 480
At scrollTop 400 rows 10 to 24 are on screen. With an overscan of three rows on each side, rows 7 to 27 are rendered: 21 nodes, however long the list. ceil matters: a row that is only partly visible at the bottom edge still needs a node.
Figure 2. A windowed list
How to read this: the accent boxes are the code you write. A scroll event updates scrollTop; the maths turns it into a range; only that range is rendered, each row positioned absolutely at its offset inside a spacer as tall as the full list. The data itself stays whole in memory.
MDN documents scrollTop as a double-precision value that may not be a whole number and, on Safari, can go beyond the scrollable range while overscrolling. A real list therefore clamps it to the range from 0 to total height minus viewport height; the lab does, and a test covers a stale value after the list shrinks.
Overscan: a margin against blank flashes
Rows are rendered after the scroll event, so a fast scroll can reveal space before new rows arrive. Overscan renders a few extra rows on each side. web.dev notes that blank space can briefly flash and that overscanning too many entries can affect performance negatively. It is a tuning knob, not a fix.
Rows of different heights
With unequal heights, "row i starts at i * 40" is false. Build prefix sums: offsets[i] is the top of row i, and offsets[n] is the total height. The first visible row is the last i with offsets[i] not above scrollTop, found by binary search in O(log n). The lab's variableRange does exactly this and its test compares it with a brute-force scan.
Figure 3. Where do the heights come from?
the same height?"} A -->|"yes"| F["Arithmetic:
two divisions"] A -->|"no"| B{"Is each height known
before rendering?"} B -->|"yes"| S["Prefix sums +
binary search"] B -->|"no"| E["Estimate, then measure and correct
(wrong estimate = wrong rows)"]
How to read this: the cheapest case is also the safest. Truncating text to a fixed row height often removes the hard case entirely; the unknown-height case is where virtualized lists get bugs.
Illustration 2: the realistic example, from the lab
The lab's VirtualList renders a role="list" scroller with a spacer and absolutely positioned rows, taking the viewport height and each row height as props.
Expected output, captured from a real run (node src/demo.ts in examples/frontend/labs/list-virtualization, copied from examples/frontend/golden/list-virtualization.txt), in full:
=== fixed heights: 10,000 rows of 40 px, viewport 600 px, overscan 3
scrollTop visible rendered rows in DOM
0 0..14 0..17 18
20 0..15 0..18 19
40 1..15 0..18 19
400 10..24 7..27 21
123456 3086..3101 3083..3104 22
399400 9985..9999 9982..9999 18
999999 9985..9999 9982..9999 18
total height: 400000 px (the spacer that keeps the scrollbar honest)
=== variable heights: rows alternate 30 px and 90 px, viewport 240 px, overscan 0
first offsets: 0, 30, 120, 150, 240, 270, 360 (offsets[i] is the top of row i)
scrollTop visible
0 0..3
100 1..5
125 2..6
1000 17..21
total height: 60000 px
=== wrong sizes: the window is computed with 50 px rows, the real rows are 30 px
rows rendered from the guess : 20..22
rows actually on screen : 33..38
rows that are both rendered and on screen: 0
Block 1: 10,000 rows give 18 to 22 rows in the DOM at every position, and a scrollTop beyond the end is clamped (the last two rows of the table are identical). The total height is 400,000 px, the spacer. Block 2: with alternating 30 px and 90 px rows (prefix sums), scrollTop 100 shows rows 1 to 5. These numbers are illustrative.
Illustration 3: a failure, from the lab
Block 3 is the failure. The window was computed with 50 px rows but the real rows are 30 px, so the code renders rows 20 to 22 while rows 33 to 38 are on screen: none of the rendered rows are visible, which is a blank list. A size estimate is an input to the arithmetic, and a wrong input gives a confident wrong answer.
What virtualization takes away
- Row state. A row that leaves the window unmounts, and with it any state held in the row (a half-typed field). Lift the state above the list and key it by item id; the lab's tests show both the loss and the fix. See React Keys, Lists and Identity for why the key must be the id, not the index.
- Find-in-page and DOM queries. Rows that are not rendered are not in the document, so the browser's search cannot find them (unlike
content-visibility: auto, which keeps them). Offer an in-app search instead. - Accessibility context. When not all items are in the DOM, MDN says to use
aria-setsizefor the true size andaria-posinsetfor the position, so a screen reader can say "item 6 of 10,000". The lab sets both. - Focus and keyboard. A focused row that scrolls out of the window unmounts. The lab does not solve this: scrolling to a row by index and keeping focus alive are the work of a real library.
Figure 4. A row loses its state
How to read this: the state either lives in the row, and dies with it, or above the list, keyed by something that survives unmounting.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Virtualize | A DOM that stays small | Lost row state, no find-in-page, extra accessibility work |
| Fixed row height | Two divisions, no measuring | Rows must be truncated or padded |
| Variable heights, known | Natural row sizes | Prefix sums to rebuild when sizes change |
| Estimated heights | No pre-known sizes | Wrong rows or jumping scrollbars until corrected |
| More overscan | Fewer blank flashes | More nodes per frame |
content-visibility: auto |
Keeps find-in-page and the accessibility tree | Nodes still exist; needs a size hint |
Build it
The lab examples/frontend/labs/list-virtualization has src/windowing.ts (fixedRange, buildOffsets, variableRange, scrollTopToReveal) and src/VirtualList.tsx. jsdom does no layout: its README lists layout as out of scope and says it returns zeros for many layout properties, so the list takes its viewport height and every row height as props, and the tests scroll by setting scrollTop and firing a scroll event. The tests count DOM nodes and check inline styles; they say nothing about smoothness, frame rate or memory.
cd examples/frontend/labs/list-virtualization
../../node_modules/.bin/vitest run
../../node_modules/.bin/tsc -p tsconfig.json
node src/demo.ts
Verified. The 42 tests in two files passed with Node 26.13.1 and Vitest 5.1.0, and the type check passed. They compare the formulas with a brute-force scan, render 10,000 rows and count the DOM nodes, clamp a stale scrollTop, place variable-height rows by cumulative height, and show row state being lost and kept. The captured demo output above is identical to the golden file.
Break it. In src/windowing.ts, in fixedRange, temporarily change Math.ceil(bottom / itemHeight) - 1 to Math.floor(bottom / itemHeight) - 1. A row that is only partly visible at the bottom edge is no longer rendered, and the window tests fail. Restore the line and re-run the tests.
In practice: a merchant stock table
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A merchant dashboard shows every product the merchant sells in one scrolling table, with an editable stock field in each row. Large merchants have around ten thousand rows (illustrative). The table takes a long time to appear and scrolling stutters.
Starting architecture
Figure 5. Every row in the DOM
How to read this: the warning boxes are where the cost lives: every row exists as nodes whether or not anyone sees it.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Paginate the table | Small DOM | A click per page | Merchants who scan the whole table dislike it |
content-visibility: auto on rows |
Skips off-screen rendering work | Nodes still exist | Scrollbar shifts without a size hint |
| Virtualize with fixed 48 px rows | Constant node count | Lost row state, no find-in-page | Truncated text; focus handling |
The decision
| Field | Decision record |
|---|---|
| Context | The table is slow to render and scroll with all rows in the DOM; merchants scan it by eye and edit stock in place. |
| Decision | Measure first, then virtualize with fixed-height rows and an overscan of a few rows. Lift the stock edits above the list, keyed by product id, and add a search box that filters the data, not the DOM. |
| Consequences, good | The node count no longer depends on the data. |
| Consequences, bad | No browser find-in-page; row text truncates; focus needs care. |
| Revisit when | Rows need variable content that cannot be truncated, or a library with measured sizes is justified. |
Rollout and verification
- Measure the table before and after with the browser's own tools; the tests in this lesson do not measure speed.
- Test the edges: an empty list, a list shorter than the viewport, a jump to the end, and a list that shrinks while scrolled.
- Test state: type into a row, scroll away and back, and check the value.
- Check a screen reader and the keyboard by hand: the lab does not verify them.
The 2 a.m. failure
After a design change rows can wrap to two lines. The code still assumes 48 px rows, so the window is computed from the wrong sizes: rows overlap and the bottom of the panel is blank, exactly as in block 3 of the demo.
First three checks: (1) compare the height the code assumes with a row's real height in the browser's inspector; (2) check whether text wrapping or a font change altered row height; (3) scroll to the end and see whether the last row is reachable. Mitigation: restore the fixed height with truncation. Follow-up: a test that renders a row with the longest realistic text and asserts it fits the assumed height.
Architect's notes
- Measure before and after. Virtualization is a performance change; it needs a performance measurement.
- Prefer fixed heights. It keeps the maths trivial and the scrollbar stable.
- Keep state above the list. Anything that must survive a scroll belongs in a store keyed by id.
- Use a library for hard cases. Variable measured sizes, focus management and scrolling to an index are better taken from a maintained library once you know the maths.
Common mistakes
- Virtualizing without measuring.
- Wrong or stale row heights, giving blank or overlapping rows.
- Index as key in a list whose data moves.
- Row-local state for something users edit.
- Forgetting
aria-setsizeandaria-posinset, so a screen reader hears only the rendered rows. - Unclamped
scrollTopafter the list shrinks.
Key takeaways
- Render only the rows near the viewport, inside a spacer as tall as the whole list.
- With equal heights the window is two divisions; with different known heights use prefix sums and binary search.
- Overscan trades blank flashes for extra nodes.
- Every size you feed the maths must be true; an estimate that is wrong renders the wrong rows.
- Virtualization drops row state, find-in-page and focus unless you plan for them.
- Try paging and
content-visibility: autofirst, and measure.
Practice exercises
Exercise 1: Starter (30 min). For rows of 36 px, a 480 px viewport and overscan 2, compute by hand the rendered range at scrollTop 1,000, then check it with the Node snippet.
Exercise 2: Intermediate (2 hours). Add a scrollToIndex prop to the lab's VirtualList that uses scrollTopToReveal, with a test.
Exercise 3: Intermediate (2 hours). Write a test that types into a row's input, scrolls away and back, and shows the value kept once the state is lifted above the list.
Exercise 4: Advanced (half day). Add onRowsRendered(start, end) and use it to load the next page of an infinite list when end is near the item count.
Related reading
In this course:
- Pagination: Offset, Cursor and Infinite Scroll: the list that only grows, and the alternative to windowing.
- React Keys, Lists and Identity: why keys must be stable ids.
- Rendering Pipeline: Layout, Paint and Compositing: what a node costs the browser.
- INP and Responsiveness: how rendering work shows up as slow interactions.
Official documentation
- web.dev: Virtualize large lists with react-window: windowing, overscan, blank space, measuring first.
- MDN: content-visibility: skipping off-screen rendering while keeping the DOM.
- web.dev: content-visibility: containment and the size hint.
- web.dev: How large DOM sizes affect interactivity: the cost of a large DOM.
- MDN: aria-setsize: the set size when only part of a set is in the DOM.
- MDN: Element.scrollTop: the scroll position as a double.