Sub topic 10
Rendering only what is visible: list virtualization
This chapter assumes you can build React function components with props, state, and hooks. It also assumes you have recorded a session in the React DevTools Profiler and can read a flamegraph, which earlier chapters covered. You do not need prior experience with a virtualization library.
When memoization is not enough
Memoization skips work for components whose props did not change. It cannot help when the work is simply large. A list of 10,000 rows has to mount 10,000 components and create their DOM nodes the first time, no matter how well each row is memoized.
You can recognize this case in the Profiler:
- The first commit (the mount) is slow, and its flamegraph shows thousands of narrow, similar bars under one parent.
- Updates stay slow even after memoizing rows, because React still compares the props of every row.
- The browser feels sluggish when scrolling, because of the large number of DOM nodes it has to lay out and paint.
Virtualization (also called windowing) addresses this by rendering only the rows that are visible in the scroll container, plus a few extra rows above and below. The rest of the list does not exist in the DOM. The cost of the list then depends on how many rows fit on screen, not on how many rows are in the data.
How virtualization works
A virtualized list needs three things:
- A scroll container with a fixed height and
overflow: auto. - A tall inner element whose height equals the total height of all rows. This makes the scrollbar look and behave as if every row were present.
- A small set of absolutely positioned rows, placed at the correct offsets, that change as the user scrolls.
With a fixed row height, the arithmetic is simple. If the container is 400px tall, each row is 40px, and scrollTop is 1,200px:
- The first visible index is
floor(1200 / 40)= 30. - The number of visible rows is
ceil(400 / 40)= 10. - The rendered range is 30 to 39, plus an overscan buffer.
A minimal fixed-height implementation
The following component is complete and runs as shown. It exists to show the mechanism. For production use, prefer a maintained library.
import { useState } from "react";
const ROW_HEIGHT = 40;
const VIEWPORT_HEIGHT = 400;
const OVERSCAN = 3;
export function VirtualList({ items }) {
const [scrollTop, setScrollTop] = useState(0);
const first = Math.max(0, Math.floor(scrollTop / ROW_HEIGHT) - OVERSCAN);
const visibleCount = Math.ceil(VIEWPORT_HEIGHT / ROW_HEIGHT) + OVERSCAN * 2;
const last = Math.min(items.length, first + visibleCount);
const rows = [];
for (let i = first; i < last; i++) {
rows.push(
<div
key={items[i].id}
style={{
position: "absolute",
top: i * ROW_HEIGHT,
height: ROW_HEIGHT,
left: 0,
right: 0,
}}
>
{items[i].name}
</div>
);
}
return (
<div
style={{ height: VIEWPORT_HEIGHT, overflow: "auto" }}
onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}
>
<div style={{ height: items.length * ROW_HEIGHT, position: "relative" }}>
{rows}
</div>
</div>
);
}Points worth noticing:
scrollTopis state, so every scroll event triggers a render ofVirtualList. That is acceptable because each render creates only about 16 rows.- The key is
items[i].id, not the loop index. Stable keys let React reuse the DOM node of a row that stays visible while the window moves. - The inner element has a height of
items.length * ROW_HEIGHT. Without it, the scrollbar would reflect only the few rendered rows.
Using a library
Real lists need variable row heights, horizontal scrolling, grids, keyboard support, and sticky headers. Maintained libraries handle these cases. Common choices are:
| Library | Style | Notes |
|---|---|---|
| react-window | Small components such as `FixedSizeList` | Lightweight and focused on lists and grids. Row sizes are given or computed by you. |
| react-virtualized | Larger component set | Older and broader. It includes `AutoSizer` and `CellMeasurer`. |
| @tanstack/react-virtual | Headless hook | You supply the markup. It supports dynamic measurement and works across frameworks. |
Here is the same list with react-window. The row component receives an index and a style object, and you must apply style to the row's root element, since it holds the absolute positioning.
import { FixedSizeList } from "react-window";
function Row({ index, style, data }) {
return <div style={style}>{data[index].name}</div>;
}
export function Items({ items }) {
return (
<FixedSizeList
height={400}
width="100%"
itemCount={items.length}
itemSize={40}
itemData={items}
>
{Row}
</FixedSizeList>
);
}Passing the data through itemData rather than closing over it keeps Row a stable component type across renders. If you define Row inline inside the parent, its identity changes each render and React remounts every visible row.
Edge cases and trade-offs
Virtualization changes how the page behaves, not only how fast it is. Consider these points before adopting it.
Variable row heights
The offset arithmetic above assumes every row has the same height. With variable heights, the library has to know or measure each height. There are two approaches:
- Provide a height per index (for example,
VariableSizeListinreact-window). This is fast but requires heights you can compute in advance. - Measure rows after they render (for example, with
@tanstack/react-virtual'smeasureElement). This is flexible, but unmeasured rows use an estimate. The scrollbar size can change as measurements arrive, which can make the thumb jump.
Things that stop working
Because off-screen rows are not in the DOM, features that rely on the DOM will miss them:
- Browser find-in-page (Ctrl+F) will not find text in rows that are not rendered.
- Screen readers see only the rendered rows. Set
aria-rowcount,aria-rowindex, or similar attributes where the pattern calls for them, and test with assistive technology. - Anchor links and
scrollIntoViewneed an index-based method, such as thescrollToItemmethod thatreact-windowlists provide. - Local state inside a row is lost when the row scrolls out and unmounts. Keep state that must survive, such as a checked box or an open editor, in a parent or in a store keyed by item id.
- Printing and server rendering produce only the visible window unless you handle them separately.
Fast scrolling and blank areas
If rows are expensive to render, a fast scroll can reveal blank space before new rows appear. Increase overscan to render more rows ahead of the viewport. Each extra row costs render time, so raise it only as far as needed. Keep rows themselves cheap, and memoize them when their props are stable.
When not to virtualize
Virtualization adds complexity. Skip it when:
- The list has a few hundred simple rows. Rendering those is usually fast enough, and the Profiler will confirm it.
- The content must be fully searchable or printable.
- Pagination or "load more" fits the product better and reduces data fetching too.
An alternative for long, mostly static content is the CSS property content-visibility: auto. It lets the browser skip layout and paint for off-screen elements while keeping them in the DOM. It does not reduce React's render cost or the DOM node count, so it helps only with browser rendering work.
Verifying the change
Follow the same measure-first approach as in earlier chapters:
- Record a Profiler session of the slow action, such as mounting the page or typing in a filter box, using a production build.
- Note the commit duration and the number of components in the flamegraph.
- Add virtualization and record the same action again.
- Compare the commit duration and component count. The mount of a 10,000-row list should drop from thousands of rows to a few dozen.
- Scroll while recording and check that individual commits stay short. In the browser Performance panel, look for long tasks during scrolling.
If scroll commits are slow even though only a few rows render, check that each row is cheap, that you did not define the row component inline, and that nothing expensive runs in the scroll handler.
Exercise
A 5,000-row list is virtualized with a 600px container and 30px rows. The scrollTop is 900px and the overscan is 2 rows on each side. Which row indexes are rendered, using the formulas from this chapter? Also, why should the row key be the item id rather than the loop index?
Show answer
The first visible index is floor(900 / 30) = 30, and minus the overscan of 2 gives 28. The visible count is ceil(600 / 30) = 20, plus 2 x 2 for overscan gives 24. The last index (exclusive) is 28 + 24 = 52, so rows 28 through 51 are rendered. The key should be the item id so that React matches each rendered row with its item as the window moves. With loop indexes as keys, a key is tied to a position rather than an item, so after the window shifts React may reuse DOM nodes for different items, which can cause extra DOM updates and mix up per-row state.
Exercise
After virtualizing a list, users report that a checkbox they ticked in a row is unticked after scrolling away and back. What causes this, and how do you fix it?
Show answer
Rows that scroll out of the window are unmounted, so state held inside the row component is discarded. Move the checked state to the parent or a store keyed by item id, and pass it to the row as a prop.