Sub topic 5
Computing which rows are visible
This chapter assumes you know React function components and useState, basic CSS positioning, and how the browser fires scroll events. You have seen the idea of windowing: render only the rows near the viewport. Here you work out which rows those are. The calculation is small, but most off-by-one errors and blank-row bugs in virtual lists come from it.
The inputs
For a list where every row has the same height, the visible range depends on four numbers:
| Input | Where it comes from | Example |
|---|---|---|
| `scrollTop` | The scroll container's `scrollTop` property, read in a scroll handler | 1000 |
| `viewportHeight` | The scroll container's visible height | 400 |
| `rowHeight` | A fixed value you choose | 40 |
| `count` | `items.length` | 10000 |
scrollTop is the distance in pixels between the top of the scrollable content and the top of the visible area. Row i occupies the vertical band from i * rowHeight to (i + 1) * rowHeight in content coordinates. The viewport covers the band from scrollTop to scrollTop + viewportHeight. A row is visible if its band overlaps the viewport's band.
The two formulas
The first visible row is the one that contains the viewport's top edge:
firstVisible = floor(scrollTop / rowHeight)The last visible row is the one that contains the viewport's bottom edge. The bottom edge is exclusive: a pixel at exactly scrollTop + viewportHeight belongs to the next row. So the last row is:
lastVisible = ceil((scrollTop + viewportHeight) / rowHeight) - 1With scrollTop = 1000, viewportHeight = 400, and rowHeight = 40:
firstVisible = floor(1000 / 40) = 25lastVisible = ceil(1400 / 40) - 1 = 35 - 1 = 34
Rows 25 to 34 are on screen, which is 10 rows. They fit exactly, because 400 divides evenly by 40.
Now scroll 10 pixels further, to scrollTop = 1010:
firstVisible = floor(1010 / 40) = floor(25.25) = 25lastVisible = ceil(1410 / 40) - 1 = ceil(35.25) - 1 = 35
Row 25 is now clipped at the top, but part of it is still visible, so it must stay rendered. Row 35 has entered at the bottom. A viewport that holds 10 rows exactly can need 11 rows in the DOM whenever the scroll position is not a multiple of the row height.
Inclusive and exclusive ends
The formulas above give an inclusive end: last is the index of the last row to render. Some libraries return an exclusive end instead, so you can write items.slice(start, end). Pick one convention and keep it everywhere. Mixing them produces a row that is either missing at the bottom or rendered one too many times.
The hand-written list in the topic's example uses Math.ceil((scrollTop + height) / rowHeight) without the - 1. That renders one extra row below the viewport. It is harmless there, because overscan renders extra rows anyway, but it is not the tight range. This chapter uses the exact version so you can reason about the edges.
A pure function for the range
Keep the calculation out of the component. A pure function is easy to test without a browser, and you can reuse it later when you add a library or variable heights.
export type Range = { start: number; end: number };
export function getVisibleRange(opts: {
scrollTop: number;
viewportHeight: number;
rowHeight: number;
count: number;
overscan?: number;
}): Range {
const { scrollTop, viewportHeight, rowHeight, count, overscan = 0 } = opts;
// Empty range: end < start, so `for (i = start; i <= end; i++)` does nothing.
if (count <= 0 || rowHeight <= 0) return { start: 0, end: -1 };
const top = Math.max(0, scrollTop);
const firstVisible = Math.floor(top / rowHeight);
const lastVisible = Math.ceil((top + viewportHeight) / rowHeight) - 1;
const start = Math.min(count - 1, Math.max(0, firstVisible - overscan));
const end = Math.min(count - 1, lastVisible + overscan);
return { start, end };
}
console.log(getVisibleRange({ scrollTop: 1000, viewportHeight: 400, rowHeight: 40, count: 10000 }));
// { start: 25, end: 34 }
console.log(getVisibleRange({ scrollTop: 1010, viewportHeight: 400, rowHeight: 40, count: 10000 }));
// { start: 25, end: 35 }
console.log(getVisibleRange({ scrollTop: 1000, viewportHeight: 400, rowHeight: 40, count: 10000, overscan: 3 }));
// { start: 22, end: 37 }
console.log(getVisibleRange({ scrollTop: 3600, viewportHeight: 400, rowHeight: 40, count: 100 }));
// { start: 90, end: 99 }
console.log(getVisibleRange({ scrollTop: 0, viewportHeight: 400, rowHeight: 40, count: 0 }));
// { start: 0, end: -1 }The fourth call is the bottom of a 100-row list. The content is 4000 px tall, so the largest useful scrollTop is 4000 - 400 = 3600. The result ends at row 99, and the clamp never has to act.
Edge cases that break naive versions
| Situation | What goes wrong without a guard | Guard |
|---|---|---|
| Empty list | `count - 1` is `-1`, so you read `items[-1]` or build a negative range | Return an empty range early |
| Negative `scrollTop` | Safari and some touch devices report negative values during rubber-band overscroll, giving a negative `start` | `Math.max(0, scrollTop)` |
| `scrollTop` past the end | The list shrinks (a filter is applied) while the user is scrolled far down, so `start` is greater than `count` | Clamp `start` and `end` to `count - 1` |
| Fractional `scrollTop` | On high-density screens it can be something like `1000.5`, so the same row boundary is crossed in different events | `floor` and `ceil` already handle this. Don't round `scrollTop` yourself. |
| Viewport height is 0 | A container that is hidden or not yet laid out gives an empty or one-row range | Measure after layout and treat 0 as "not ready" |
| Row height of 0 or `NaN` | Division gives `Infinity` or `NaN`, which produces an infinite loop or no rows | Reject `rowHeight <= 0` |
A filter that shrinks the list is the case people forget. The browser clamps the container's real scrollTop after the spacer shrinks, and it fires a scroll event when it does. But your stored scrollTop or range can still be stale for one render. The clamps make that render safe.
Using the range in a component
The simplest approach stores scrollTop in state and derives the range during render. That re-renders on every scroll event, even when the range does not change. At 10 px of scroll per event and 40 px rows, most of those renders produce the same rows.
You can avoid that by storing the range instead, and returning the previous object when nothing changed. React skips the re-render when a state updater returns the same reference.
import { useCallback, useState, type UIEvent } from "react";
import { getVisibleRange, type Range } from "./getVisibleRange";
export function useVisibleRange(
count: number,
viewportHeight: number,
rowHeight: number,
overscan = 3
) {
const [range, setRange] = useState<Range>(() =>
getVisibleRange({ scrollTop: 0, viewportHeight, rowHeight, count, overscan })
);
const onScroll = useCallback(
(e: UIEvent<HTMLElement>) => {
const next = getVisibleRange({
scrollTop: e.currentTarget.scrollTop,
viewportHeight,
rowHeight,
count,
overscan,
});
setRange((prev) =>
prev.start === next.start && prev.end === next.end ? prev : next
);
},
[count, viewportHeight, rowHeight, overscan]
);
return { range, onScroll };
}Content that is not a multiple of the viewport
Two details affect the numbers around the edges.
First, the spacer height is count * rowHeight. The largest possible scrollTop is that value minus the viewport height. At that position lastVisible equals count - 1 exactly, so the end clamp only matters once overscan is added.
Second, browsers cap the height of a single element. The limit differs by browser, at roughly 17 million pixels in Firefox and 33 million in Chrome. With 40 px rows, a list of about 800,000 rows reaches the Chrome limit, and past it the spacer stops growing. Positions near the end become wrong. Lists that large usually need server-side paging or a scroll-scaling technique, and you should check them by testing in each target browser.
Checking your range
You can confirm the range against the real DOM. Render the list, scroll to a known position, and compare the first and last rendered indexes with your function. A cheap invariant also catches many bugs: the number of rendered rows should stay near ceil(viewportHeight / rowHeight) + 1 + 2 * overscan. If the count grows as you scroll, you are leaking rows, usually because the range or the key values are wrong.
Exercise
A list has rowHeight 50, a viewport of 300 px, and 200 rows. With overscan 0, what range does the inclusive formula give at scrollTop = 475, and how many rows are rendered?
Show answer
firstVisible = floor(475 / 50) = 9. lastVisible = ceil((475 + 300) / 50) - 1 = ceil(15.5) - 1 = 15. The range is rows 9 to 15, which is 7 rows. Six rows fill the viewport exactly, and a seventh is needed because the scroll position is not a multiple of 50.
Exercise
Your range function returns end = count - 1 + overscan for a list scrolled to the bottom, and the app throws "Cannot read properties of undefined". Which line fixes the bug, and why did the error only appear at the bottom?
Show answer
Clamp the end with Math.min(count - 1, lastVisible + overscan). Away from the bottom, lastVisible + overscan is below count - 1, so every index points to a real item. At the bottom, the overscan pushes the end past the last item, and items[end] is undefined, which the row component then dereferences.