Sub topic 13
Combining Virtualization with Infinite Loading
This chapter assumes you have built the fixed-height list and used useVirtualizer from TanStack Virtual in earlier chapters. You should also be comfortable with useState, useRef, and useEffect.
Virtualization limits how many rows are in the DOM. Infinite loading limits how many rows you fetch. The two work well together, but they answer different questions. This chapter connects them with one rule: when the virtualizer renders a row near the end of the loaded data, fetch the next page.
Two Separate Problems
Without virtualization, an infinite list grows the DOM with every page. After twenty pages you have the slowdown from the first chapter, even though each request was small.
Without infinite loading, a virtual list needs the whole data set in memory up front. That costs a large download and a slow first paint.
Combined, the DOM stays small and the network traffic stays incremental. The memory held in the items array still grows, but arrays of plain objects are much cheaper than DOM nodes.
The Core Idea: A Sentinel Row
The virtualizer knows which row indexes are visible. You can use that as your scroll trigger instead of an IntersectionObserver or a scroll listener. Check whether the last rendered virtual row is the last loaded item.
A common refinement is to tell the virtualizer there is one more row than you have data for. This extra row is a loader row. It shows a spinner while loading, and it reserves space at the bottom so the scrollbar reflects that more content is coming.
The diagram below shows the cycle.
A Paged Data Hook
First, a data source. This example fakes a server that returns 50 items per page and 1,000 items in total. The hook tracks the cursor, an in-flight flag, and an error.
import { useCallback, useEffect, useRef, useState } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
type Page = { items: string[]; nextCursor: number | null };
const PAGE_SIZE = 50;
const TOTAL = 1000;
async function fetchPage(cursor: number): Promise<Page> {
await new Promise((resolve) => setTimeout(resolve, 400));
const items: string[] = [];
for (let i = cursor; i < Math.min(cursor + PAGE_SIZE, TOTAL); i++) {
items.push(`Row ${i}`);
}
const next = cursor + PAGE_SIZE;
return { items, nextCursor: next < TOTAL ? next : null };
}
function usePagedItems() {
const [items, setItems] = useState<string[]>([]);
const [hasMore, setHasMore] = useState(true);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const cursorRef = useRef(0);
const inFlightRef = useRef(false);
const loadMore = useCallback(async () => {
if (inFlightRef.current) return;
inFlightRef.current = true;
setIsLoading(true);
setError(null);
try {
const page = await fetchPage(cursorRef.current);
setItems((prev) => [...prev, ...page.items]);
if (page.nextCursor === null) {
setHasMore(false);
} else {
cursorRef.current = page.nextCursor;
}
} catch (e) {
setError(e instanceof Error ? e : new Error(String(e)));
} finally {
inFlightRef.current = false;
setIsLoading(false);
}
}, []);
return { items, hasMore, isLoading, error, loadMore };
}The inFlightRef guard matters. Effects can fire several times before React re-renders with isLoading set to true, and React Strict Mode runs effects twice in development. A ref updates synchronously, so it blocks duplicate requests that state would miss.
The Virtual List With a Loader Row
Now connect the hook to the virtualizer. The count is items.length + 1 while more data exists. The last index is the loader row.
export function InfiniteList() {
const { items, hasMore, isLoading, error, loadMore } = usePagedItems();
const parentRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
count: hasMore ? items.length + 1 : items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 35,
overscan: 5,
});
const virtualItems = virtualizer.getVirtualItems();
const lastItem = virtualItems[virtualItems.length - 1];
const lastIndex = lastItem ? lastItem.index : -1;
useEffect(() => {
if (lastIndex >= items.length - 1 && hasMore && !isLoading && !error) {
loadMore();
}
}, [lastIndex, items.length, hasMore, isLoading, error, loadMore]);
return (
<div ref={parentRef} style={{ height: 400, overflow: "auto" }}>
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
{virtualItems.map((v) => {
const isLoaderRow = 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)`,
}}
>
{isLoaderRow ? (
error ? (
<button onClick={loadMore}>Failed. Retry</button>
) : (
"Loading more…"
)
) : (
items[v.index]
)}
</div>
);
})}
</div>
</div>
);
}Follow what happens on first render. items is empty, so count is 1. The virtualizer renders index 0, which is the loader row. Then lastIndex (0) is at least items.length - 1 (-1), so the effect calls loadMore. The same condition handles both the initial load and every later page, so there is no separate "load on mount" code.
How Early Should You Fetch?
The effect fires when the last rendered row is at the end of the loaded data. The virtualizer renders overscan rows beyond the viewport, so the loader row enters the rendered range five rows before the user can see it. That is your built-in prefetch distance.
To fetch earlier, change the condition rather than raising overscan:
const PREFETCH_DISTANCE = 15;
if (lastIndex >= items.length - 1 - PREFETCH_DISTANCE && hasMore && !isLoading && !error) {
loadMore();
}A larger distance hides latency on slow networks. The cost is that you fetch pages the user may never reach. Keep overscan small, because it controls DOM size, and tune the prefetch distance separately.
Edge Cases
Errors Must Stop the Loop
The effect runs whenever its dependencies change. If a request fails and the effect does not check error, it fires again immediately and you get an endless retry loop. The example above blocks auto-loading while error is set, and the loader row renders a retry button that calls loadMore directly.
Short Pages and Tall Viewports
If the first page does not fill the viewport, the loader row stays in the rendered range after the data arrives. The effect runs again and fetches the next page, repeating until the viewport is full. This works without extra code, but it is a reason to keep page sizes larger than the number of rows that fit on screen.
Resetting on a New Query
When a filter or search term changes, you must clear the items, reset the cursor, and ignore responses from the old query. A late response from query A can otherwise append rows to the results for query B. Store a request counter in a ref, capture its value when the request starts, and drop the response if it no longer matches. Also scroll the container back to the top with virtualizer.scrollToOffset(0).
Stable Keys Across Pages
The virtualizer's v.key defaults to the row index. That is fine for append-only data. If pages can overlap, or items can be removed, supply getItemKey: (index) => items[index]?.id ?? index so row identity follows the data. Also deduplicate by id when you merge a page, since cursor-based APIs can return an item twice if the data changes between requests.
Loading Older Items at the Top
Chat-style lists load upward. Prepending rows shifts every existing row's offset, so the user's view jumps unless you adjust the scroll position by the height you added. This is considerably harder than appending. The library's scrollToIndex with an index shifted by the page size is the usual starting point, and dynamic row heights make it harder still.
Summary of the Pattern
| Piece | Purpose |
|---|---|
| `count = items.length + 1` | Reserves a loader row and keeps the scrollbar honest |
| Last virtual index in an effect | Triggers fetching without scroll math |
| `inFlightRef` | Blocks duplicate requests |
| `error` check | Stops retry loops |
| Prefetch distance | Hides latency without raising overscan |
| `getItemKey` with ids | Keeps row identity stable when pages change |
Exercise
A developer sets count: items.length (no extra loader row) and runs the fetch effect when lastIndex >= items.length - 1. The list loads the first page only if it already has items, and otherwise shows nothing forever. Why does it never load the first page, and what is the smallest change that fixes it?
Show answer
With no items, count is 0, so the virtualizer renders no rows. lastIndex stays -1, which is not less than items.length - 1 (also -1), so the condition is technically true. However, if the effect is gated on a rendered last item existing, nothing ever triggers it, and the loader row that would reserve space and report an index is missing. The smallest fix is to use count: hasMore ? items.length + 1 : items.length, so the loader row at index 0 is rendered on the first pass. Its index triggers loadMore, and the same code then handles every later page.
Exercise
Your effect checks hasMore && !isLoading but not error. The server starts returning 500 responses. What happens in the browser, and how do you fix it?
Show answer
Each failure sets isLoading back to false and the effect runs again, so the app sends requests in a tight loop until the server recovers or the user leaves. Fix it by adding !error to the condition. loadMore clears the error when it starts, so a retry button in the loader row can call loadMore directly to resume.