Topic F6
Virtualizing long lists
Creating only the visible rows: a sliding window for lists of thousands.
Watch: of 1,000 rows, only the ones visible on screen are actually created. As you scroll, the window moves along.
- moving now
Why lots of elements are slow
Every DOM element uses memory and has to be styled, laid out and painted. A 10,000-row list with 5 elements per row is 50,000 elements. The first render can take seconds, every small change triggers expensive relayout, and scrolling stutters on cheap phones. Google suggests keeping a page under roughly 1,400 DOM elements.
How it works
- Know every row's height (or measure it the first time it shows).
- From the scroll position, work out the first visible row:
Math.floor(scrollTop / rowHeight). - Render only from that row to the last one that fits on screen, plus a few spare rows (overscan) so fast scrolling doesn't flash empty gaps.
- Put those rows inside a container as tall as the whole list, shifted with
transform, so the scrollbar stays right.
Code, for programmersWith TanStack Virtual
import { useVirtualizer } from "@tanstack/react-virtual";
function BigList({ rows }) {
const parentRef = useRef(null);
const v = useVirtualizer({
count: rows.length, // 10,000 rows
getScrollElement: () => parentRef.current,
estimateSize: () => 36, // px per row
overscan: 5,
});
return (
<div ref={parentRef} style={{ height: 400, overflow: "auto" }}>
<div style={{ height: v.getTotalSize(), position: "relative" }}>
{v.getVirtualItems().map((item) => (
<div key={item.key} style={{ position: "absolute", top: 0, width: "100%",
transform: `translateY(${item.start}px)` }}>
{rows[item.index].name}
</div>
))}
</div>
</div>
);
}Quiz
A 50,000-row list, 10 rows fit on screen, overscan 3. Roughly how many rows are in the DOM with virtualization?
Why is the container made as tall as the whole list?
What's a downside of virtualization?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.