Sub topic 3
The windowing idea: render only what is visible
This chapter assumes you know React function components, useState, useRef and useEffect, and basic CSS positioning and overflow scrolling. It also assumes you know that scrolling fires scroll events on an element. The previous chapters showed why a list of thousands of rows is slow and how to measure it. This chapter introduces the technique that fixes it, without building the full component yet.
The core idea
A user looking at a list of 10,000 rows sees about 10 of them. The other 9,990 rows are mounted as React elements and DOM nodes, laid out by the browser, and kept up to date on every re-render, yet nobody sees them.
Windowing (also called virtualization) removes that waste. It mounts only the rows inside a window around the visible area, and it changes which rows are mounted as the user scrolls. The rest of the list exists only as data in an array.
To the user, the list still looks like 10,000 rows. The scrollbar has the right size and thumb position, and scrolling is continuous. Only the mounted DOM is small.
The three things a windowed list must fake
A normal list gets three behaviors for free from the browser. A windowed list has to reproduce each one.
| Behavior | Normal list | Windowed list |
|---|---|---|
| Total scrollable height | Sum of all row heights, computed by layout | Computed by your code and applied to a spacer element |
| Row position | Rows stack in document flow | Each mounted row is placed at its own offset |
| Which rows exist | All of them | Only the rows in the visible range plus a margin |
The next two chapters cover the first two rows of this table in detail: the scroll container, the spacer, and absolute positioning, then the arithmetic for the visible range. Here you only need the shape of the solution.
A worked example in numbers
Suppose each row is 40 px tall, the list has 10,000 rows, and the scroll container is 400 px tall.
| Quantity | Value |
|---|---|
| Total content height | 10,000 × 40 = 400,000 px |
| Rows visible at once | 400 / 40 = 10 |
| Margin of extra rows above and below (overscan) | 3 each |
| Maximum rows mounted | 10 + 3 + 3 = 16, or 17 when a row is partly visible at both edges |
| Share of the list mounted | About 0.16% |
When the user scrolls to the middle, the scroll offset is about 200,000 px. The first visible row is 200000 / 40 = 5000. The mounted rows are around index 4997 to 5013. Rows 0 to 4996 and 5014 to 9999 are not in the DOM at all.
The cost of an update now depends on the window size (about 16 rows), not on the list length (10,000 rows). Doubling the data does not double the render time.
The update loop
A windowed list repeats one cycle every time the scroll position changes.
React's reconciliation does most of the work in step E. When the window moves by one row, one row unmounts and one mounts. Rows that stay in the window keep their keys, so React reuses their DOM nodes.
The idea in code
The following component shows the central move, rendering a slice instead of the whole array. The window position is fixed in this example. Wiring it to scrolling comes in later chapters.
type WindowedProps = {
items: string[];
first: number;
count: number;
};
function WindowedRows({ items, first, count }: WindowedProps) {
const visible = items.slice(first, first + count);
return (
<ul>
{visible.map((text, i) => (
<li key={first + i}>{text}</li>
))}
</ul>
);
}
export default function App() {
const items = Array.from({ length: 10000 }, (_, i) => `Row ${i}`);
return <WindowedRows items={items} first={5000} count={16} />;
}This renders 16 li elements from a 10,000-item array. Two details matter:
- The key is
first + i, the row's index in the full array. If you usedi, the key of the row at the top of the window would always be 0. When the window moves by one row, React would see every row as the same element with new text, and it would update all of them instead of adding one and removing one. sliceis cheap for a plain array, so the extra work per update is small. The saving comes from the DOM and React elements you avoid creating.
This version is incomplete, because the list is as tall as 16 rows and cannot scroll through 10,000. The spacer element in the next chapter fixes that.
Where the cost goes
Windowing helps because each of these costs scales with the number of mounted rows:
- React creates and diffs an element per row on each render.
- The browser stores a DOM node per row and its styles.
- Layout and paint work grows with the number of nodes.
- Memory grows with nodes and with any per-row component state.
Windowing does not remove costs that scale with the data array itself. Sorting, filtering, and fetching 10,000 items still cost the same. If your slow part is a filter running on every keystroke, windowing will not help, and you should have found that when you measured.
What windowing takes away
The technique trades browser conveniences for speed. Each of these gets its own chapter later, so this is a preview.
- Find-in-page. The browser can only search text that is in the DOM. Rows outside the window are invisible to Ctrl+F.
- Row state. A row that scrolls out of the window unmounts, and its local state (a typed input value, an expanded panel) is lost. State that must survive needs to live in the parent or in a store, keyed by item ID.
- Row heights. Fixed heights make the arithmetic trivial. If heights vary, you must measure rows, and positions below a measured row shift.
- Accessibility. Screen readers cannot tell that a list has 10,000 items if only 16 exist. You need attributes such as
aria-rowcountoraria-setsize, plusaria-posinseton each row. - Size limits. Browsers cap the height of an element at roughly 17 to 33 million pixels, depending on the browser. At 40 px per row, a few hundred thousand rows already approach the lower cap. Beyond that you need another approach, such as scaling the scroll position.
Common errors
These mistakes appear often in first implementations:
- Using the window-relative index as the key. As described above, this makes React update every row on each scroll instead of one. Use the item's ID or its absolute index.
- Rendering the window but forgetting the spacer. The container then has no scroll range, so the user cannot reach rows beyond the first window.
- Putting
scrollTopin state without thinking about frequency. Scroll events fire many times per frame. EachsetStatetriggers a render. For a small window this is fine, because React batches updates and re-renders cheaply. If the row components are expensive, memoize them (React.memo) so unchanged rows do not re-render. - Computing the range from the wrong element. The range depends on the scroll offset of the scroll container, not of
window. A list inside a scrolling page needs the offset relative to the list. - Assuming the window is exactly the visible rows. Without a margin, fast scrolling shows blank space before the next render lands. The overscan chapter handles this.
Windowing compared with other fixes
Windowing is one of three common answers to a long list.
| Approach | Rows in the DOM | Keeps native find-in-page | Complexity |
|---|---|---|---|
| Render everything | All | Yes | None |
| Windowing | About 10 to 30 | No | High |
| Pagination | One page | Within the page only | Medium |
| CSS `content-visibility: auto` | All | Yes | Low |
Windowing gives the largest reduction in DOM size and works when users must scroll continuously through very large data. Pagination and content-visibility suit cases where you can accept their limits. The last chapter of this tutorial covers how to choose.
Exercise
A list has 50,000 rows of 32 px each, shown in a 480 px tall scroll container with an overscan of 4 rows on each side. How tall is the content the spacer must represent, how many rows are visible at once, and what is the most rows you would expect to mount? Also, why should the key of each mounted row be its index in the full array instead of its position within the window?
Show answer
The total height is 50,000 × 32 = 1,600,000 px. The visible rows are 480 / 32 = 15. With overscan, the window is 15 + 4 + 4 = 23 rows, or 24 if a row is partly visible at both edges. A window-relative key gives the top row the same key (0) every time the window moves, so React would reuse that element for different data and update every row on each scroll step. An absolute index or an item ID keeps each row's identity stable, so React adds one row and removes one.