Sub topic 7
Overscan: avoiding blank gaps while scrolling
This chapter assumes you can read React function components, use useState and useRef, and understand position: relative and position: absolute. It also assumes you know that the browser fires scroll events on an element with overflow: auto. You should have the fixed-height virtual list from the previous chapter in mind: a scroll container, a spacer, and absolutely positioned rows between a computed first and last index.
The problem: the window is exactly the viewport
A virtual list renders only the rows that intersect the viewport. If you render exactly those rows and nothing else, you have a timing problem. The browser scrolls on its own compositor thread, so the pixels move before React knows anything happened. Your onScroll handler runs afterward, calls setScrollTop, and React renders new rows on a later frame. For a short time the user sees the new scroll position but the old rows. The part of the viewport that has no rows yet is blank.
Fast scrolling makes the gap larger. A mouse wheel flick, a trackpad fling, or dragging the scrollbar thumb can move the content by thousands of pixels between two renders. Slow devices make it worse, because each render takes longer.
Overscan is the fix. Overscan means rendering a few extra rows beyond each edge of the visible range. Those rows are already in the DOM when the user scrolls toward them, so the scroll can move a short distance before the list needs to catch up.
How overscan fits into the visible range
Here is the range calculation from the hand-written list, reduced to the part that matters:
const first = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
const last = Math.min(
items.length - 1,
Math.ceil((scrollTop + height) / rowHeight) + overscan
);Without overscan, first is the index of the row at the top edge and last is the index of the row at the bottom edge. With overscan, first moves up by overscan rows and last moves down by overscan rows. Two clamps keep the indexes valid. Math.max(0, ...) stops first from going negative near the top. Math.min(items.length - 1, ...) stops last from passing the final item near the bottom.
The number of rendered rows is therefore roughly:
- visible rows, which is
height / rowHeightrounded up, plus - up to
2 * overscanextra rows, fewer near either end of the list.
With a 400px container, 40px rows, and overscan = 3, about 10 rows are visible and up to 16 are rendered.
Seeing the gap and the fix
The following component is complete and runnable. It lets you change overscan with a slider and shows how many rows are in the DOM. Set overscan to 0 and drag the scrollbar thumb quickly. You will often see a white strip before rows appear, especially if you throttle the CPU in your browser's developer tools.
import { useState } from "react";
type Props = {
items: string[];
height: number;
rowHeight: number;
overscan: number;
};
function List({ items, height, rowHeight, overscan }: Props) {
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,
borderBottom: "1px solid #ddd",
}}
>
{items[i]}
</div>
);
}
return (
<div>
<p>Rendered rows: {rows.length}</p>
<div
style={{ height, overflow: "auto", border: "1px solid #999" }}
onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}
>
<div style={{ height: items.length * rowHeight, position: "relative" }}>
{rows}
</div>
</div>
</div>
);
}
const items = Array.from({ length: 50000 }, (_, i) => `Row ${i}`);
export default function OverscanDemo() {
const [overscan, setOverscan] = useState(0);
return (
<div>
<label>
Overscan: {overscan}
<input
type="range"
min={0}
max={20}
value={overscan}
onChange={(e) => setOverscan(Number(e.target.value))}
/>
</label>
<List items={items} height={400} rowHeight={40} overscan={overscan} />
</div>
);
}The row count changes as you move the slider, and so does the visible behavior. That gives you a direct way to choose a value for your own list.
Choosing a value
Overscan trades render cost against scroll smoothness. Each extra row costs one more component render, more DOM nodes, and more layout work. Each missing row is a chance for a blank gap.
| Overscan | Effect | Typical use |
|---|---|---|
| 0 | Fewest DOM nodes, most visible gaps | Very heavy rows, or when you measure and find gaps acceptable |
| 3 to 5 | Covers normal wheel and keyboard scrolling | Default for simple text rows |
| 10 to 20 | Covers fast flings on slower devices | Light rows, long scroll distances per frame |
| Large values | Approaches rendering the whole list | Defeats the purpose of virtualizing |
Three factors move the right number up or down:
- Row cost. If each row contains images, charts, or many child components, extra rows are expensive. Keep overscan small and make the rows cheaper.
- Row height. Short rows mean a given pixel distance covers many rows. A 20px row needs a larger overscan than a 100px row to cover the same distance.
- Target devices. A fast desktop rarely shows gaps at 3. A low-end phone may need more.
Count overscan in rows, not pixels. If your rows are very different in height, a row count covers an uneven distance. Some libraries and hand-written lists therefore offer an overscan measured in pixels instead.
Overscan in TanStack Virtual
useVirtualizer takes an overscan option that works the same way, counted in items:
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
export function List({ items }: { items: string[] }) {
const parentRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 35,
overscan: 5,
});
return (
<div ref={parentRef} style={{ height: 400, overflow: "auto" }}>
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
{virtualizer.getVirtualItems().map((v) => (
<div
key={v.key}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: v.size,
transform: `translateY(${v.start}px)`,
}}
>
{items[v.index]}
</div>
))}
</div>
</div>
);
}Here overscan: 5 makes getVirtualItems() return five extra items on each side of the visible range. The library clamps at the list ends for you, so you do not write the Math.max and Math.min calls yourself. The returned items include the overscan rows, so your map renders them without any special handling.
Side effects of overscan
Overscan rows are real rows. They are mounted, they run effects, and they can fetch data or start animations.
- Mount-time effects. A row that loads an image or fires a request in
useEffectwill do so for overscan rows even though the user cannot see them yet. This is often a benefit, since the data is ready by the time the row scrolls in. It is a cost if each fetch is expensive. - Visibility logic. Do not treat "is rendered" as "is visible." Analytics code that logs an impression when a row mounts will over-count. Use an
IntersectionObserverif you need true visibility. - Focus and find. Overscan rows are reachable by Tab and by browser find-in-page, even though they are off screen. This is mostly harmless, but it means focus can land on a row the user has not seen.
- Range churn. A larger overscan does not change how often the range changes, but each change renders more rows. If you see dropped frames while scrolling, lower overscan before you look elsewhere.
Common errors
- Forgetting the clamps. Without
Math.max(0, ...), the first row index goes negative near the top, anditems[-1]isundefined. WithoutMath.min(items.length - 1, ...), the loop reads past the end. - Setting overscan very high to hide a slow row. This renders hundreds of expensive rows and makes scrolling worse. Fix the row cost or reduce the overscan.
- Overscan in an unbounded container. If the scroll container has no fixed height, the viewport height is the whole list and the range covers every row. Overscan then has no effect, and neither does virtualization.
- Tuning on a fast machine only. Gaps appear on slow hardware. Test with CPU throttling in the browser's performance tools, and measure before and after changing the value.
Exercise
A virtual list has a 600px container and 30px rows. The overscan is 4. The user has scrolled so that scrollTop is 3000. The list has 10,000 items. Which indexes are first and last, and how many rows render?
Show answer
first = max(0, floor(3000 / 30) - 4) = 100 - 4 = 96. last = min(9999, ceil((3000 + 600) / 30) + 4) = 120 + 4 = 124. Rows 96 to 124 render, which is 29 rows. Twenty rows are visible (600 / 30), and 4 overscan rows sit on each side, but the row at index 100 is the first visible one and index 120 sits exactly at the bottom edge boundary, so the ceil includes it, which accounts for the extra row.
Exercise
Your list has rows that each load a 200KB image in useEffect. Users report that scrolling feels janky, and the network panel shows many image requests for rows the user never saw. What do you change first, and why?
Show answer
Lower the overscan, because every overscan row mounts and fires its image request even though it is off screen. Reducing overscan from, say, 15 to 3 cuts the number of mounted rows and requests per scroll step. If the gaps return, make the row cheaper, for example by using smaller thumbnails or lazy loading, instead of raising overscan again.