How to Implement Virtual Scrolling
Render only the visible rows of a long list, keeping the DOM small so a list of thousands stays smooth.
On this page
Introduction
A list of ten thousand rows rendered as ten thousand DOM nodes is slow to build, slow to lay out, and heavy in memory, even though only a screenful is visible. Virtual scrolling, or windowing, renders only the rows in view plus a small overscan, and positions them to match the scroll offset. The user sees a normal scrolling list, but the DOM holds a few dozen nodes instead of ten thousand. This article covers the windowing math, measuring item height, handling variable heights, and the accessibility and search concerns the technique introduces.
Why Virtualize
The browser must create, lay out, style and paint every node in the document. Ten thousand rows is a visible cost at mount, and any change to the list re-runs part of it. Because scrolling only changes which rows are visible, most of that work is invisible to the user, and windowing removes it by rendering only what is visible.
The trade is complexity: the component must track the scroll offset, compute which items are visible, and keep the scrollbar the correct length so the scroll thumb reflects the full list. As long as those are correct, the user cannot tell the difference except that it is fast.
Windowing the List
The core calculation is: from the scroll offset and the viewport height, find the first and last visible indices, render those plus a small overscan, and offset them within a container whose height is the total list height. The tall container keeps the scrollbar accurate; the rendered rows are absolutely positioned at their offset.
import { useRef, useState, useEffect } from 'react';
function VirtualList<T>({ items, itemHeight, render }: Props<T>) {
const ref = useRef<HTMLDivElement>(null);
const [scrollTop, setScrollTop] = useState(0);
const [viewport, setViewport] = useState(600);
useEffect(() => {
const el = ref.current;
if (!el) return;
const onScroll = () => setScrollTop(el.scrollTop);
el.addEventListener('scroll', onScroll, { passive: true });
const resize = () => setViewport(el.clientHeight);
resize();
window.addEventListener('resize', resize);
return () => { el.removeEventListener('scroll', onScroll); window.removeEventListener('resize', resize); };
}, []);
const overscan = 5;
const start = Math.max(0, Math.floor(scrollTop / itemHeight) - overscan);
const end = Math.min(items.length, Math.ceil((scrollTop + viewport) / itemHeight) + overscan);
const visible = items.slice(start, end);
return (
<div ref={ref} style={{ overflowY: 'auto', height: '100%', position: 'relative' }}>
{/* Spacer keeps the scrollbar proportional to the full list. */}
<div style={{ height: items.length * itemHeight, position: 'relative' }}>
{visible.map((item, i) => (
<div key={(start + i)} style={{ position: 'absolute', top: (start + i) * itemHeight, height: itemHeight, left: 0, right: 0 }}>
{render(item)}
</div>
))}
</div>
</div>
);
}
Measuring Item Height
Fixed height is the simple case: the math above is exact and fast. Variable height is harder, because the position of an item depends on the heights of all items before it. Two approaches: measure each rendered item and maintain an estimated-then-measured height map, or require the caller to provide a height function.
Maintain a prefix-sum of heights so the offset of item i is the sum of the heights before it, and update it as items are measured. The scrollbar length changes as heights are learned, which is why a fixed estimate for unmeasured items keeps the scroll position stable while the real heights arrive.
A binary search over the prefix-sum finds the first visible index for a given scroll offset in logarithmic time, which keeps the visible-range calculation cheap even for a list of hundreds of thousands of items. Without the prefix-sum you would walk the heights to find the offset, which is linear and defeats the purpose of windowing.
// Maintain a prefix-sum of measured heights and estimate the unmeasured.
class HeightIndex {
constructor(count, estimate) {
this.count = count;
this.estimate = estimate;
this.measured = new Float64Array(count); // 0 means not yet measured
}
heightAt(i) { return this.measured[i] || this.estimate; }
offsetOf(i) { // O(i) to build, cached in practice
let sum = 0;
for (let k = 0; k < i; k++) sum += this.heightAt(k);
return sum;
}
total() { return this.offsetOf(this.count) ; }
setMeasured(i, h) {
if (this.measured[i] !== h) {
this.measured[i] = h;
// Recompute the offset of everything after i (or call onLayout below).
}
}
}
Dynamic Heights
With dynamic heights, render an estimated height for unmeasured items and correct the estimate when the real height is measured, adjusting the prefix-sum and the total. The tricky part is scroll anchoring: when an item above the viewport changes height, the content below shifts, so the scroll offset must be adjusted to keep the visible content in place.
Use a library for dynamic heights where possible, because scroll anchoring and measurement timing are subtle; implementing them by hand is a common source of jumpy scrolling. The library keeps the same windowing idea and handles the measurement and anchoring for you.
Estimate the unmeasured height close to the real one, from a sample of measured items or from a known average, so the total length is approximately right and the scrollbar does not jump as heights arrive. A poor estimate makes the scroll thumb move visibly, which looks like a bug even though the content is correct.
Accessibility and Search
Virtualization breaks browser find-on-page, because only the visible rows exist in the DOM. It also affects screen readers, which cannot read rows that are not rendered. Provide a search or a way to jump to an item so finding a value does not rely on the browser search, and keep the accessible structure valid, for example by using a list role with the correct count and position.
For full accessibility, expose the total item count and the visible range through ARIA so a screen reader knows the list length even though only part is in the DOM. Test with a screen reader and with keyboard navigation, because focus that scrolls off the window must still work.
Conclusion
Virtual scrolling renders only the visible rows plus a small overscan, positioned within a container sized to the full list so the scrollbar stays accurate. Fixed heights make the math exact; variable heights need measurement and scroll anchoring, which a library handles better than hand-rolled code. Keep the visible-range calculation cheap with a prefix-sum and a binary search, and estimate the unmeasured height closely so the scrollbar does not jump. Accept that find-on-page and screen-reader traversal are limited, and provide search and ARIA metadata to compensate. Then a list of thousands scrolls as smoothly as one of dozens.
Sources: react-window, TanStack Virtual, MDN: ARIA live regions.
FAQ
- Why is find-on-page broken with virtual scrolling?
- Because only the visible rows are in the DOM, and the browser can only search what is rendered. Rows scrolled out of the window do not exist, so they cannot be found. Provide an in-app search or a jump-to-item instead.
- Should I implement variable-height virtualization myself?
- Prefer a maintained library. Measurement timing and scroll anchoring for variable heights are subtle, and a hand-rolled version tends to produce jumpy scrolling and wrong offsets. Fixed heights are simple enough to implement directly.
Report a problem with this articleOpens a pre-filled issue on GitHub.