Infinite Scroll Virtualized Table
Combine virtual scrolling with infinite loading to handle large paginated datasets without a heavy DOM.
Renders only the on-screen rows (with @tanstack/react-virtual) and fetches the next page as the user nears the end. Use it for any paginated API that can grow past a few hundred rows. Memory and frame time stay flat no matter how many pages load.
Preview with Controlled State
Introduction
Section titled “Introduction”The Infinite Scroll Virtualized Table combines two separate performance tricks:
- Virtualization: only rows in the viewport are rendered to the DOM, however many are loaded. Needed for thousands of rows.
- Infinite loading: rows are fetched as the user scrolls, so you never load the full dataset upfront.
You get both by combining two pieces:
DataTableVirtualizedBody: the virtualized scroll container. It firesonScrolledBottom.DataTableVirtualizedLoadingMore: the “loading more” child. It shows itself based on its ownisFetchingprop.
This example pages through a mocked 5,000-row pool with artificial delay, so you can see the virtualizer and the infinite loader work together.
Installation
Section titled “Installation”Install the DataTable core and add-ons for this example:
pnpm dlx shadcn@latest add @niko-table/data-table @niko-table/data-table-virtualized @niko-table/data-table-search-filter @niko-table/data-table-view-menu @niko-table/data-table-column-sortFirst time using
@niko-table? See the Installation Guide to set up the registry.
Prerequisites
Section titled “Prerequisites”We are going to build a virtualized table that paginates through a large list of products. Here’s what our data looks like:
type Product = { id: string name: string category: string price: number stock: number status: "in-stock" | "low-stock" | "out-of-stock"}Implementation
Section titled “Implementation”Deterministic mock data generator
Section titled “Deterministic mock data generator”Like the non-virtualized Infinite Scroll Table, the mock generator is fully deterministic: index-based values, no Math.random(), no Date.now(). That keeps the example safe to copy into a Next.js or RSC app without server/client hydration mismatches.
const CATEGORIES = [ "Electronics", "Clothing", "Food", "Books", "Sports", "Home", "Toys", "Beauty",] as const
function generateMockProducts(count: number): Product[] { return Array.from({ length: count }, (_, i) => { const stock = (i * 37) % 150 const price = ((i * 13) % 490) + 10 return { id: `product-${i + 1}`, name: `Product ${i + 1}`, category: CATEGORIES[i % CATEGORIES.length], price, stock, status: stock === 0 ? "out-of-stock" : stock < 20 ? "low-stock" : "in-stock", } })}
// Larger pool than the non-virtualized example — 5,000 rows split// into 50 pages of 100, so virtualization's value is visible.const TOTAL_POOL = generateMockProducts(5000)const PAGE_SIZE = 100const FAKE_LATENCY_MS = 800
function fetchNextPage(offset: number): Promise<Product[]> { return new Promise(resolve => { setTimeout(() => { resolve(TOTAL_POOL.slice(offset, offset + PAGE_SIZE)) }, FAKE_LATENCY_MS) })}Pagination state + loadMore handler
Section titled “Pagination state + loadMore handler”Same as the non-virtualized example: three pieces of state (loaded, isLoading, isFetching), one loadMore handler guarded against running twice, and one derived hasMore boolean.
const [loaded, setLoaded] = React.useState<Product[]>([])const [isLoading, setIsLoading] = React.useState(true)const [isFetching, setIsFetching] = React.useState(false)
const hasMore = loaded.length < TOTAL_POOL.length
React.useEffect(() => { let cancelled = false void fetchNextPage(0).then(page => { if (cancelled) return setLoaded(page) setIsLoading(false) }) return () => { cancelled = true }}, [])
const loadMore = React.useCallback(async () => { if (isFetching || !hasMore) return setIsFetching(true) try { const nextPage = await fetchNextPage(loaded.length) setLoaded(prev => [...prev, ...nextPage]) } finally { setIsFetching(false) }}, [isFetching, hasMore, loaded.length])<DataTableVirtualizedBody /> with onNearEnd + <DataTableVirtualizedLoadingMore />
Section titled “<DataTableVirtualizedBody /> with onNearEnd + <DataTableVirtualizedLoadingMore />”For infinite scroll, the virtualized body gives you a better trigger: onNearEnd. It is driven by the virtualizer’s row index, not by scroll events. It fires when the last rendered virtual row is within prefetchThreshold rows of the end of the loaded data.
How it compares to onScrolledBottom:
| Scenario | onScrolledBottom |
onNearEnd |
|---|---|---|
| Slow scroll reaches bottom | fires | fires (earlier) |
| Fast wheel scroll past bottom | fires once, gap before resolve | fires early, no gap |
| Scrollbar drag to 90% | may miss | fires as soon as virtualizer re-renders |
| Initial load, data < viewport | never fires (no scroll) | fires immediately |
scrollToIndex() jump |
no scroll event | fires on re-render |
| Row height changes dynamically | pixel math drifts | index math is exact |
"use client"
import * as React from "react"import { DataTableRoot } from "@/components/niko-table/core/data-table-root"import { DataTable } from "@/components/niko-table/core/data-table"import { DataTableVirtualizedHeader, DataTableVirtualizedBody, DataTableVirtualizedEmptyBody, DataTableVirtualizedSkeleton, DataTableVirtualizedLoadingMore,} from "@/components/niko-table/core/data-table-virtualized-structure"import { DataTableSearchFilter } from "@/components/niko-table/components/data-table-search-filter"import { DataTableToolbarSection } from "@/components/niko-table/components/data-table-toolbar-section"import { DataTableViewMenu } from "@/components/niko-table/components/data-table-view-menu"
export function InfiniteScrollVirtualizedTable() { // ... state + loadMore from the previous section ...
return ( <DataTableRoot data={loaded} columns={columns} isLoading={isLoading} config={{ initialPageSize: 5000 }} > <DataTableToolbarSection> <DataTableSearchFilter placeholder="Search products..." /> <DataTableViewMenu /> </DataTableToolbarSection>
<DataTable height={600} className="rounded-lg border"> <DataTableVirtualizedHeader /> <DataTableVirtualizedBody prefetchThreshold={15} onNearEnd={() => { if (hasMore && !isFetching) void loadMore() }} > <DataTableVirtualizedSkeleton rows={15} /> <DataTableVirtualizedEmptyBody /> <DataTableVirtualizedLoadingMore isFetching={isFetching}> Loading more products... </DataTableVirtualizedLoadingMore> </DataTableVirtualizedBody> </DataTable> </DataTableRoot> )}Required: Fixed Height
Section titled “Required: Fixed Height”Virtualized tables always need a fixed height on <DataTable>. The virtualizer needs a scroll container with a known size to decide which rows to render.
<DataTable height={600} className="rounded-lg border"> {/* ... */}</DataTable>How DataTableVirtualizedLoadingMore works with the virtualizer
Section titled “How DataTableVirtualizedLoadingMore works with the virtualizer”DataTableVirtualizedLoadingMore is a plain child of TableBody. It sits outside the virtualizer’s row count. This matters because:
- It doesn’t affect
estimateSizemath. The virtualizer computes total scroll height fromrows.length × estimateSize. If the loading row were a virtual row, adding it would shift every row after it. - It renders at the bottom of the viewport, however far the user has scrolled.
- It shows itself based on
isFetching. Render it always. It appears only while a fetch is in flight.
onNearEnd vs onScrolledBottom
Section titled “onNearEnd vs onScrolledBottom”Both work on DataTableVirtualizedBody. For infinite scroll, use onNearEnd:
onNearEnd: driven by the virtualizer’s row index. Fires when the last rendered virtual row is withinprefetchThresholdrows of the end.- Catches fast scrolls, scrollbar drags,
scrollToIndex()jumps, and first renders where data doesn’t fill the viewport. - Fires once per false-to-true change (no double fires).
- Catches fast scrolls, scrollbar drags,
onScrolledBottom: driven by scroll events. Fires when the user scrolls withinscrollThresholdpixels of the bottom.- Easier to reason about, and fine for non-infinite uses (for example, analytics “user reached bottom”).
- Misses the edge cases above.
Pattern: wiring TanStack Query’s useInfiniteQuery
Section titled “Pattern: wiring TanStack Query’s useInfiniteQuery”When you swap the mock data for a real API, this maps directly onto TanStack Query’s useInfiniteQuery:
const query = api.products.list.useInfiniteQuery( { limit: 100 }, { getNextPageParam: p => p.nextCursor },)
const loaded = query.data?.pages.flatMap(p => p.rows) ?? []
<DataTableRoot data={loaded} columns={columns} isLoading={query.isLoading}> <DataTable height={600}> <DataTableVirtualizedHeader /> <DataTableVirtualizedBody prefetchThreshold={15} onNearEnd={() => { if (query.hasNextPage && !query.isFetchingNextPage) { void query.fetchNextPage() } }} > <DataTableVirtualizedSkeleton rows={15} /> <DataTableVirtualizedEmptyBody /> <DataTableVirtualizedLoadingMore isFetching={query.isFetchingNextPage}> Loading more products... </DataTableVirtualizedLoadingMore> </DataTableVirtualizedBody> </DataTable></DataTableRoot>No extra boilerplate: isFetching comes straight from the query, and onNearEnd calls fetchNextPage.
When to Use
Section titled “When to Use”✅ Use Infinite Scroll Virtualized Table when:
- Your paginated API can return thousands of rows in one session
- Rendering every loaded row would bloat the DOM (over 1000 rows loaded)
- Users expect smooth scrolling through a growing list
- You already use virtualization for performance
❌ Don’t use it when:
- Your pool is small (under 1000 rows total): the plain Infinite Scroll Table is simpler
- You need row DnD: virtualized row DnD plus infinite scroll gives two sources of row order
- You need variable row heights: the virtualizer works best with even row heights
Next Steps
Section titled “Next Steps”- Infinite Scroll Table: non-virtualized variant for smaller pools
- Virtualization Table: virtualization without infinite scroll
- Server-Side Table: traditional pagination with server-driven sort/filter