Skip to content
Niko Table

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.

infinite-scroll-virtualized-table.tsx
Name
Category
Price
Stock
Status
Brand
Rating
Revenue
Release Date
Loaded 0 of 5000 products
Preview with Controlled State
infinite-scroll-virtualized-table-state.tsx
Name
Category
Price
Stock
Status
Brand
Rating
Revenue
Release Date
Loaded 0 of 5000 products
Infinite Scroll Virtualized Table State
Live view of the controlled table state with 5,000 total products
Search Query:None
Total Items:5,000
Loaded Rows:0
Active Filters:0 (Search Only)
Expanded Rows:0
Sorting:None
Page:1 (Size: 5000)
Hidden Columns:0
Pinned Columns:0 Left, 0 Right
View Full State Object
Sorting:
[]
Expanded Rows:
{}
Pagination:
{
  "pageIndex": 0,
  "pageSize": 5000
}
Column Visibility:
{}
Column Pinning:
{
  "start": [],
  "end": []
}

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 fires onScrolledBottom.
  • DataTableVirtualizedLoadingMore: the “loading more” child. It shows itself based on its own isFetching prop.

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.

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-sort

First time using @niko-table? See the Installation Guide to set up the registry.

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"
}

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.

mock-data.ts
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 = 100
const 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)
})
}

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
infinite-scroll-virtualized-table.tsx
"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>
)
}

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:

  1. It doesn’t affect estimateSize math. The virtualizer computes total scroll height from rows.length × estimateSize. If the loading row were a virtual row, adding it would shift every row after it.
  2. It renders at the bottom of the viewport, however far the user has scrolled.
  3. It shows itself based on isFetching. Render it always. It appears only while a fetch is in flight.

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 within prefetchThreshold rows 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).
  • onScrolledBottom: driven by scroll events. Fires when the user scrolls within scrollThreshold pixels 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.

✅ 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