Sub topic 2
Computing Which Rows Are Visible
This chapter assumes you know React function components, useState, basic CSS positioning, and how scroll events work.
Calculate the visible range
A fixed-height row has the same height, such as 40 pixels. If scrollTop is the number of pixels scrolled and height is the viewport height:
- The first visible row is
floor(scrollTop / rowHeight). - The last visible row is
ceil((scrollTop + height) / rowHeight). - Clamp both indexes so they stay within the item array.
A spacer keeps the scrollbar proportional to the full list. The rendered rows are positioned inside that spacer.
Build a fixed-height virtual list
import { useState } from "react";
export function VirtualList({ items }: { items: string[] }) {
const height = 300;
const rowHeight = 40;
const [scrollTop, setScrollTop] = useState(0);
const first = Math.max(0, Math.floor(scrollTop / rowHeight) - 3);
const last = Math.min(
items.length - 1,
Math.ceil((scrollTop + height) / rowHeight) + 3
);
return (
<div
style={{ height, overflow: "auto" }}
onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}
>
<div style={{ height: items.length * rowHeight, position: "relative" }}>
{Array.from({ length: Math.max(0, last - first + 1) }, (_, offset) => {
const index = first + offset;
return (
<div
key={index}
style={{
position: "absolute",
top: index * rowHeight,
height: rowHeight,
left: 0,
right: 0,
}}
>
{items[index]}
</div>
);
})}
</div>
</div>
);
}Overscan prevents blank gaps
Overscan renders rows just outside the viewport. Without it, a fast scroll can move past the currently rendered range before React commits the next rows. Three extra rows above and below is a reasonable starting point. Increase it when rows are expensive to render or scrolling is especially fast. Reduce it when rendering work or memory matters more.
Use a virtualization library
TanStack Virtual handles range calculation, overscan, scrolling, and measurement:
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 40,
overscan: 5,
});Use a library when row heights vary, rows need measurement, or you need reliable scrolling to an index. A hand-written list is useful when heights are fixed and the behavior is simple.
Exercise
Why does the virtual list need both a full-height spacer and absolutely positioned rows?
Show answer
The spacer preserves the scrollbar's full-list geometry, while absolute positioning places only the rendered rows at their correct indexes.