Sub topic 6
Building a fixed-height virtual list
This chapter assumes you know React function components, useState, basic CSS positioning (relative, absolute), and how scroll events work. You will build a virtual list by hand. It handles rows that all have the same height, and it renders only the rows near the viewport.
The three pieces
A fixed-height virtual list is made of three nested parts:
- The scroll container. A
divwith a fixedheightandoverflow: auto. It owns the scrollbar and is the only element that scrolls. - The spacer. A child
divwhose height isitems.length * rowHeight. It holds no content. It makes the scroll container believe the whole list is present, so the scrollbar has the right length and thumb size. - The rows. Only a small slice of the list is rendered. Each row is absolutely positioned inside the spacer at
top: index * rowHeight.
The spacer needs position: relative so the rows' top values are measured from its top edge. A row at index 5000 with rowHeight 40 sits 200,000 px down inside the spacer. It does not matter that rows 0 to 4999 are not in the DOM, because absolute positioning does not depend on siblings.
Computing the visible range
The viewport shows everything between scrollTop and scrollTop + height. Dividing by the row height converts pixels to row indexes:
- The first visible row is
Math.floor(scrollTop / rowHeight). A row that is half scrolled out of view still counts, so you round down. - The last visible row is
Math.ceil((scrollTop + height) / rowHeight). A row that is only partly in view still counts, so you round up.
Then you add overscan, a few extra rows on each side, and clamp the result to the valid index range. The clamping keeps you from reading index -3 at the top or past the end of the array at the bottom. A later chapter covers overscan in depth. Here it is a single number that makes the rendered slice slightly larger than the viewport.
With height = 400, rowHeight = 40, overscan = 3, and a long list, the numbers look like this:
| `scrollTop` | Floor part | Ceil part | `first` | `last` | Rows rendered |
|---|---|---|---|---|---|
| 0 | 0 | 10 | 0 | 13 | 14 |
| 2000 | 50 | 60 | 47 | 63 | 17 |
| 2010 | 50 | 61 | 47 | 64 | 18 |
The number of rendered rows stays near 14 to 18 whether the list has 1,000 items or 1,000,000.
The component
import { useState } from "react";
type VirtualListProps = {
items: string[];
height: number;
rowHeight: number;
overscan?: number;
};
export function VirtualList({ items, height, rowHeight, overscan = 3 }: VirtualListProps) {
const [scrollTop, setScrollTop] = useState(0);
const first = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
const last = Math.min(
items.length - 1,
Math.ceil((scrollTop + height) / rowHeight) + overscan
);
const rows = [];
for (let i = first; i <= last; i++) {
rows.push(
<div
key={i}
style={{
position: "absolute",
top: i * rowHeight,
left: 0,
right: 0,
height: rowHeight,
}}
>
{items[i]}
</div>
);
}
return (
<div
style={{ height, overflow: "auto" }}
onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}
>
<div style={{ height: items.length * rowHeight, position: "relative" }}>
{rows}
</div>
</div>
);
}To try it, render it with a large array:
import { VirtualList } from "./VirtualList";
const items = Array.from({ length: 100_000 }, (_, i) => `Row ${i}`);
export default function App() {
return <VirtualList items={items} height={400} rowHeight={40} />;
}Open the browser's Elements panel and scroll. The spacer's children change as you move, and there are never more than about 20 of them.
How it works, line by line
- State holds only
scrollTop. Everything else is derived during render.first,last, and the row elements are plain values computed from props and one number. Storing them in state would create values that can drift out of sync withscrollTop. e.currentTarget.scrollTop.currentTargetis the element the handler is attached to, which is the scroll container.targetcould be a descendant, so usecurrentTarget.items.length * rowHeight. This is the whole reason the scrollbar looks normal. ChangerowHeightand both the spacer and every row position change together.left: 0; right: 0. The row stretches across the spacer without a hard-coded width.key={i}. The key is the row's index, so the key identifies a position in the list. A later chapter on keys and row state explains when to use an item ID instead.
Edge cases
Empty list. With items.length === 0, last is -1, the loop does not run, and the spacer has height 0. The component renders an empty container and does not crash.
Short list. If the list is shorter than the container, last is clamped to items.length - 1 and every row renders. The spacer is shorter than the container, which is fine.
List shrinks while scrolled. Suppose the user is at scrollTop 8000 and items drops to 10 rows. The browser clamps the real scrollTop to 0 and usually fires a scroll event, but your state can be stale for one render. In that render first is greater than last, so nothing renders, and the list corrects itself on the next scroll event. If you filter or replace the list often, reset the scroll position deliberately. For example, set scrollTop to 0 on the container through a ref when the data source changes.
Very tall spacers. Browsers cap the maximum height of an element, at roughly 17 to 33 million pixels depending on the browser. At a 40 px row height, that is somewhere between 400,000 and 800,000 rows. Beyond that, the spacer stops growing and the bottom of the list becomes unreachable. Libraries do not remove this limit, so lists of this size need paging or a server-side window instead.
Rows must be exactly rowHeight tall. The range math assumes every row is rowHeight pixels. If the content of a row wraps and grows, it overflows into the next row's space, because rows are absolutely positioned and do not push each other down. Fix the height with overflow: hidden and text-overflow: ellipsis, or move to the dynamic measurement approach in a later chapter.
Performance characteristics
Each scroll event calls setScrollTop, which re-renders VirtualList. The work per render is proportional to the number of visible rows, not to the list length. That is the gain. There are still costs to know about:
- One render per scroll event. Browsers fire scroll events at most once per frame, and React batches the state update, so this is usually fine. Expensive row components can still make scrolling choppy. Wrap them in
React.memoand keep their props stable. - Re-render when the slice has not changed. Scrolling 1 px changes
scrollTopbut often leavesfirstandlastthe same. React still re-runs the component and diffs the same rows. Libraries avoid this by storing the range, not the raw pixel offset, so a re-render only happens when the range changes. - Row churn. As you scroll, rows leave and enter the DOM. A row that scrolls away loses its local state, such as a text input's contents or an expanded panel. Keep state like that in the parent, keyed by item ID.
Where this design stops
This implementation does one thing: fixed-height rows in a vertical list. It does not support rows with different heights, scrolling to a given index, horizontal scrolling, or keyboard and screen reader semantics. Later chapters add those, using TanStack Virtual, which handles the same job with the same spacer-and-positioned-rows structure. If you understand this component, you understand what the library does internally.
Exercise
A list has 50,000 rows, rowHeight is 30, the container height is 300, and overscan is 2. The user has scrolled to scrollTop = 6015. Which indexes does the component render, and how many rows is that?
Show answer
first = max(0, floor(6015 / 30) - 2) = floor(200.5) - 2 = 200 - 2 = 198. last = min(49999, ceil((6015 + 300) / 30) + 2) = ceil(210.5) + 2 = 211 + 2 = 213. The component renders indexes 198 to 213, which is 16 rows.
Exercise
A teammate changes the spacer's style from { height: items.length * rowHeight, position: "relative" } to { position: "relative" }. What happens, and why?
Show answer
The spacer has no explicit height, and its only children are absolutely positioned, so it collapses to a height of 0. The scroll container then has no overflow, so it shows no scrollbar and cannot scroll. The user sees only the rows that fit at the top of a 0-height box (clipped away), so the list appears empty or stuck. The spacer's explicit height is what gives the container its scrollable length.