Sub topic 13
Combining virtualization with infinite loading
This chapter assumes you can build a fixed-height virtual list and use useVirtualizer from TanStack Virtual. It also assumes you know useEffect and have seen a paginated fetch. Here you will load more data as the user nears the end of a virtualized list.
Why the two fit together
Virtualization limits how many rows are in the DOM. It does not limit how many items sit in memory. If the server has a million rows, you still need a way to fetch them in pages. Infinite loading supplies that. Virtualization then keeps rendering cheap as the loaded array grows.
The virtualizer knows which rows are on screen. That tells you when the user is close to the end of the loaded data, and that is the moment to fetch the next page.
Add a loader row
A common pattern is to make the list one row longer than the data while more pages remain. That extra row shows a "Loading..." placeholder and gives the virtualizer something to scroll to.
import { useEffect, useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
type InfiniteListProps = {
items: string[];
hasNextPage: boolean;
isFetching: boolean;
fetchNextPage: () => void;
};
export function InfiniteList({
items,
hasNextPage,
isFetching,
fetchNextPage,
}: InfiniteListProps) {
const parentRef = useRef<HTMLDivElement>(null);
const count = hasNextPage ? items.length + 1 : items.length;
const virtualizer = useVirtualizer({
count,
getScrollElement: () => parentRef.current,
estimateSize: () => 35,
overscan: 5,
});
const virtualItems = virtualizer.getVirtualItems();
const lastItem = virtualItems[virtualItems.length - 1];
useEffect(() => {
if (!lastItem) return;
if (lastItem.index >= items.length - 1 && hasNextPage && !isFetching) {
fetchNextPage();
}
}, [lastItem?.index, items.length, hasNextPage, isFetching, fetchNextPage]);
return (
<div ref={parentRef} style={{ height: 400, overflow: "auto" }}>
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
{virtualItems.map((v) => {
const isLoader = v.index >= items.length;
return (
<div
key={v.key}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: v.size,
transform: `translateY(${v.start}px)`,
}}
>
{isLoader ? "Loading..." : items[v.index]}
</div>
);
})}
</div>
</div>
);
}The effect reads the last rendered virtual item. Because of overscan, that index is a few rows past what the user sees, so the fetch starts slightly early. Raise overscan, or change the trigger to items.length - 1 - threshold, to fetch earlier.
Common errors
- Duplicate fetches. Without the
isFetchingguard, the effect can fire again before the first request finishes. Always guard on in-flight state. - Missing loader row. If
countequalsitems.length, the last item is a real row. The effect then fires only when the user reaches it, which can show a pause at the bottom. - Unstable keys. Appending is safe with index keys. Prepending items, such as older chat messages, shifts every index and breaks row state. Use stable IDs through the
getItemKeyoption. - Scroll jumps on prepend. When you add rows above the viewport, the scroll offset no longer points at the same content. Adjust
scrollTopby the height you added, or callscrollToIndexafter the update. - Total size changes.
getTotalSize()grows with each page, so the scrollbar thumb shrinks. This is expected. Do not try to show the true total unless the server tells you the count.
Exercise
Why does the fetch effect check !isFetching before calling fetchNextPage, and what happens if the check is removed?
Show answer
The effect runs on every render where the last visible index is near the end. While a request is still pending, the condition stays true, so each re-render would start another request for the same page. The result is duplicate network calls and possibly duplicated items. The isFetching guard allows only one request at a time.