Sub topic 14
Grids and Horizontal Virtualization
This chapter assumes you have read the earlier chapters. You should know how a fixed-height virtual list works: a scroll container, a spacer, absolutely positioned rows, and a visible range computed from scrollTop. You should also be comfortable with useVirtualizer from TanStack Virtual, including estimateSize and overscan.
One axis, then two
A vertical virtual list answers one question: which row indexes intersect the viewport? The same idea works on any axis. Two cases follow from it:
- A horizontal list uses the same math with
scrollLeft, viewport width, and item width. - A grid needs two ranges, one for rows and one for columns. It renders the cells where the two ranges cross.
No new mechanism is involved. You run the range computation once per axis and combine the results.
Horizontal virtualization
Swap the roles of the dimensions. The spacer gets the full width instead of the full height. Each item is positioned with left or translateX, and the range comes from scrollLeft and the viewport width.
In TanStack Virtual, set horizontal: true. The virtualizer then reads scrollLeft and measures widths. Its items report start and size along the horizontal axis.
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
export function HorizontalList({ items }: { items: string[] }) {
const parentRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
horizontal: true,
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 120,
overscan: 3,
});
return (
<div ref={parentRef} style={{ width: 600, height: 80, overflow: "auto" }}>
<div
style={{
width: virtualizer.getTotalSize(),
height: "100%",
position: "relative",
}}
>
{virtualizer.getVirtualItems().map((v) => (
<div
key={v.key}
style={{
position: "absolute",
top: 0,
left: 0,
height: "100%",
width: v.size,
transform: `translateX(${v.start}px)`,
}}
>
{items[v.index]}
</div>
))}
</div>
</div>
);
}Compared with the vertical version, three things change. The spacer's width comes from getTotalSize(). Each item has an explicit width and a translateX. The scroll container has a fixed width and overflow: auto.
Right-to-left layouts
In a right-to-left page, scrollLeft is zero at the right edge and negative as you scroll left in modern browsers. Positions computed from it will be wrong unless the library handles the direction. TanStack Virtual exposes an isRtl option for this. If your app supports RTL, test horizontal lists in an RTL document before shipping.
Virtualizing a grid
A grid has a row axis and a column axis. Use two virtualizers on the same scroll element. One tracks vertical scroll and one tracks horizontal scroll. The spacer takes its height from the row virtualizer and its width from the column virtualizer.
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
type GridProps = { rows: number; cols: number };
export function Grid({ rows, cols }: GridProps) {
const parentRef = useRef<HTMLDivElement>(null);
const rowVirtualizer = useVirtualizer({
count: rows,
getScrollElement: () => parentRef.current,
estimateSize: () => 35,
overscan: 5,
});
const columnVirtualizer = useVirtualizer({
horizontal: true,
count: cols,
getScrollElement: () => parentRef.current,
estimateSize: () => 100,
overscan: 2,
});
return (
<div ref={parentRef} style={{ width: 600, height: 400, overflow: "auto" }}>
<div
style={{
height: rowVirtualizer.getTotalSize(),
width: columnVirtualizer.getTotalSize(),
position: "relative",
}}
>
{rowVirtualizer.getVirtualItems().map((row) =>
columnVirtualizer.getVirtualItems().map((col) => (
<div
key={`${row.key}:${col.key}`}
style={{
position: "absolute",
top: 0,
left: 0,
width: col.size,
height: row.size,
transform: `translate(${col.start}px, ${row.start}px)`,
}}
>
r{row.index} c{col.index}
</div>
))
)}
</div>
</div>
);
}The nested map is the whole idea. Each cell is positioned with both offsets, and the cell key combines the row key and column key so that each cell stays stable as the window moves.
How many cells actually render
The cost of a grid is the product of the two ranges, not their sum. Overscan on both axes multiplies.
| Setup | Rows rendered | Columns rendered | Cells in the DOM |
|---|---|---|---|
| 600 x 400 viewport, 35px rows, 100px columns, no overscan | about 12 | about 7 | about 84 |
| Same viewport, row overscan 5, column overscan 2 | about 22 | about 11 | about 242 |
| Same viewport, overscan 10 on both axes | about 32 | about 27 | about 864 |
Overscan that is cheap in a list can become expensive in a grid. Start with a small column overscan (1 or 2) and raise it only if you see blank gaps during horizontal scrolling. The grid above still renders a few hundred cells whether the data set has a thousand cells or ten million.
Variable widths and heights in a grid
You can give estimateSize a function of the index. This works well for known column widths, such as a table whose columns have different widths:
const columnWidths = [60, 220, 120, 120, 300, 90];
const columnVirtualizer = useVirtualizer({
horizontal: true,
count: columnWidths.length,
getScrollElement: () => parentRef.current,
estimateSize: (index) => columnWidths[index],
overscan: 1,
});If widths are known ahead of time, prefer this to measuring. Measuring means rendering a cell, reading its size, and correcting the layout. For columns that is wasteful, because every cell in a column should share a width.
If you do need dynamic sizes, the rules from the earlier chapter on dynamic measurement still apply:
- Give cells
data-indexandref={virtualizer.measureElement}. - Measure along one axis only per virtualizer. For a grid, let the row virtualizer measure heights and give columns fixed or known widths.
- When column widths change from outside, for example when the user resizes a column, call
columnVirtualizer.measure()so cached sizes are discarded.
If a cell's height depends on its content and the row height must fit the tallest cell in that row, grids get hard. Only the rendered cells are measured, so a tall cell that is off-screen horizontally does not contribute to the row height. Avoid this by fixing row heights, or by using a single-line cell style with truncation.
Pitfalls specific to grids
- Sticky headers and first columns. Absolutely positioned cells inside one scroll container do not support
position: stickythe way table cells do. Render the header row as a separate element outside the spacer and sync its horizontal offset toscrollLeft. Alternatively, pin the header using the virtualizer'srangeExtractorso index 0 is always included, then useposition: stickyon that row. - Re-rendering the whole window on every scroll. In a grid, each scroll event can change two ranges. Wrap the cell component in
React.memoand pass stable props, so cells that stay in the window do not re-render. - Cell count creep. Large overscan, large viewports, and wide screens all increase the cross product. Measure the DOM node count in the browser's Elements panel rather than assuming it is small.
- Nested scroll containers. A grid inside a page that also scrolls can confuse wheel and touch behavior. Give the grid a fixed height and let it own its own scrolling.
- Accessibility. A grid of absolutely positioned
divelements has no table semantics. If the data is tabular, addrole="grid",aria-rowcount,aria-colcount, and on each cellrole="gridcell"witharia-rowindexandaria-colindex. Indexes are one-based.
<div role="grid" aria-rowcount={rows} aria-colcount={cols}>
{/* rows and cells with aria-rowindex and aria-colindex */}
</div>When a grid library is the better choice
Two virtualizers cover simple grids. If you also need column resizing, sorting, pinned columns, and row selection, use a table library for state and let TanStack Virtual handle only rendering. TanStack Table plus TanStack Virtual is a common pairing. The table library supplies the row model and column definitions, and the virtualizer decides which rows and columns to render.
Exercise
A grid has 100,000 rows and 50 columns. The viewport shows about 15 rows and 8 columns. You use a row overscan of 5 and a column overscan of 3 (applied on each side). Roughly how many cells are rendered, and why does adding column overscan cost more than adding the same amount of row overscan?
Show answer
Rows rendered: 15 + 5 + 5 = about 25. Columns rendered: 8 + 3 + 3 = about 14. Cells: about 25 x 14 = 350. Each extra column of overscan adds one cell per rendered row, which is about 25 cells per column. Each extra row of overscan adds one cell per rendered column, which is about 14 cells per row. So an extra column costs more here because there are more rendered rows than columns. In general, overscan on an axis costs in proportion to the number of items rendered on the other axis.