React Table Server-Side Pagination: TanStack + React Query

Implement server-side pagination in React with TanStack Table and React Query: page state, useQuery keys, total counts, cursors, and real production pitfalls.

Huifer
Huifer
October 24, 20269 min read
Also available in:Deutsch · 中文

Written by Huifer

I use TanStack Table for the view model and TanStack Query for the server-state lifecycle because keeping those responsibilities separate makes pagination easier to reason about. When I build a table, I first define the request contract, then connect URL state, query keys, and table state. I have not attached a production benchmark to this article; the examples are implementation guidance rather than measured performance claims.

Official references: TanStack · TanStack Table pagination · TanStack Query · TanStack Router · Cloudflare Workers · web.dev · MDN

Last updated: 2026-10-24 · Changelog

TanStack Table React Query Pagination: Best Practices

TanStack Table React Query pagination works best when the table owns presentation state and TanStack Query owns the server response. For most SaaS admin tables, use server-side pagination, put the page and page size in a stable query key, and return enough metadata for the table to know how many pages exist. This guide is for React developers deciding whether to implement pagination in an existing app or choose a template whose data layer already supports it. If the surrounding architecture matters, you can compare SaaS templates and boilerplates before committing to an implementation.

TL;DR

  • Use client-side pagination only when the complete dataset is intentionally loaded into the browser.
  • Use server-side pagination when the API, database, permissions, or filters determine the visible rows.
  • Keep pageIndex and pageSize in the query key so navigation produces the correct request.
  • Use placeholderData: keepPreviousData when you want the previous page to remain visible during a fetch.
  • Return rowCount or pageCount from the API instead of guessing it in the component.

Standalone answer: TanStack Table handles pagination state and row rendering, while TanStack Query fetches and caches each page. The reliable pattern is a shared pagination state, a query key containing that state, and an API response with explicit total-row metadata.

What TanStack Table React Query pagination means

TanStack Table is headless: it gives you table state, row models, and pagination behavior, but it does not decide how your data reaches the browser. TanStack Query manages asynchronous server data, caching, refetching, and loading transitions. The TanStack Table pagination guide documents the boundary between client-side and manual server-side pagination, while the TanStack Query overview explains the server-state layer.

Client-side versus server-side pagination

Client-side pagination means the browser receives all rows and slices them locally. Server-side pagination asks for one page at a time. Neither choice is automatically faster; the right choice depends on ownership, authorization, filters, and whether the browser should receive the complete dataset.

DecisionClient-side paginationServer-side pagination
DatasetAlready loaded in the browserQueried from an API or database
FiltersApplied locallyApplied in the request contract
PermissionsData is already exposedEnforced before rows are returned
MetadataTable can count local rowsAPI returns rowCount or pageCount
Best fitSmall, bounded datasetsSaaS records, audit logs, billing data

The buyer decision behind the implementation

The buyer decision is whether a starter already has a typed server-data boundary, URL state, and permission-aware list endpoint. A template cannot define your domain query, but it can reduce repeated wiring around routing, loading, authentication, and deployment. Inspect its query cache, navigation behavior, and pagination metadata before choosing.

The TanStack Ship templates category is the relevant product surface when you want to compare that foundation rather than copy a table component into an otherwise unrelated stack.

Design the pagination contract first

A stable contract prevents most TanStack Table and TanStack Query pagination bugs. Define pageIndex, pageSize, allowlisted sort, serialized filters, and rowCount before writing the hook. The count must reflect filters and authorization.

The browser should send a small, serializable request. URLSearchParams gives you a standard encoding model; see the MDN URLSearchParams reference. Validate every value again on the server because client validation is not an authorization boundary.

A typed response shape

This response is deliberately simple: the table needs rows and a count, while the query layer needs a predictable promise and error path.

typescript
// api/orders.ts
export type OrderPage = {
  rows: Order[]
  rowCount: number
}

export type OrderPageRequest = {
  pageIndex: number
  pageSize: number
  status?: "open" | "paid" | "refunded"
}

export async function fetchOrders(
  request: OrderPageRequest,
  signal?: AbortSignal,
): Promise<OrderPage> {
  const params = new URLSearchParams({
    page: String(request.pageIndex + 1),
    pageSize: String(request.pageSize),
  })

  if (request.status) params.set("status", request.status)

  const response = await fetch(`/api/orders?${params}`, { signal })
  if (!response.ok) throw new Error("Unable to load orders")
  return response.json() as Promise<OrderPage>
}

The + 1 converts zero-based table state to a one-based API. Test the first and last page explicitly. The TanStack Query query key guide covers request variables as cache identity.

Query keys must include every request variable

If status changes but the query key does not, the component can display a page from the wrong filter. If pageSize changes but the key only includes pageIndex, cached data can be reused under an incompatible request. Include every variable that changes the returned rows.

tsx
import {
  keepPreviousData,
  useQuery,
} from "@tanstack/react-query"

const paginationKey = [
  "orders",
  { pageIndex, pageSize, status },
] as const

const ordersQuery = useQuery({
  queryKey: paginationKey,
  queryFn: ({ signal }) =>
    fetchOrders({ pageIndex, pageSize, status }, signal),
  placeholderData: keepPreviousData,
})

keepPreviousData is a transition choice, not a correctness mechanism. Show that a new page is fetching so previous rows are not mistaken for current results. See the paginated queries documentation.

Connect TanStack Table to the query state

For server-side pagination, set manualPagination: true so the table does not slice the response again. Pass rowCount so it can derive page count. See the manual pagination section.

tsx
import {
  getCoreRowModel,
  useReactTable,
} from "@tanstack/react-table"

const table = useReactTable({
  data: ordersQuery.data?.rows ?? [],
  columns,
  getCoreRowModel: getCoreRowModel(),
  manualPagination: true,
  rowCount: ordersQuery.data?.rowCount ?? 0,
  state: { pagination: { pageIndex, pageSize } },
  onPaginationChange: setPagination,
})

The important invariant is that the same state reaches both queryKey and state.pagination. See the TanStack Table controlled state guide when another owner must synchronize with the table.

Reset the page when filters change

A filter can make the current page invalid. If page 8 narrows to two pages, pageIndex 7 produces an empty result. Reset to page 0 when a filter or sort changes.

For shareable lists, store pagination and filters in router search parameters. TanStack Router search parameters provides the typed routing model; avoid maintaining divergent URL and component copies.

Handle loading, errors, and empty pages

Pagination has more states than “rows or no rows.” Separate initial loading from a background transition, disable duplicate navigation, provide retry behavior, distinguish filtered emptiness from an out-of-range page, and invalidate affected queries after mutations.

The TanStack Query invalidation guide is the right place to reason about refreshing list queries after writes. Do not manually patch every page unless you have a clear consistency model; invalidation is often easier to verify.

Specific implementation boundaries

Problem: The table shows duplicated rows after changing page size.

Root cause: The old page remained in the query key or the table continued to apply a client-side row model to server-paginated data.

Solution: Include pageSize in the key, set manualPagination: true, and reset pageIndex to zero when size changes.

Result: The UI requests and renders one well-defined server page. This is a correctness result, not a measured performance claim.

Problem: A user can request an unauthorized page or filter.

Root cause: The endpoint trusts query-string fields and only checks permissions in the React component.

Solution: Validate page bounds, allowlist sort fields, and apply tenant or user scope in the server query. Cloudflare Workers documentation and Cloudflare D1 documentation are starting points when that endpoint runs at the edge with a database-backed request.

Result: The browser receives only rows permitted by the server-side policy. Application-specific authorization tests are still required.

Performance and accessibility checks

Pagination improves the amount of data transferred per request, but it does not automatically make a table accessible or fast. Measure the user-visible result with a representative dataset and realistic network conditions. web.dev Web Vitals covers the user-centric metrics to watch, while the MDN HTTP overview explains the request and response behavior underneath your fetch call.

I check these details before calling the table ready:

  • Page, total-page, and loading states are exposed to assistive technology.
  • Previous and Next controls disable at the correct boundaries.
  • Keyboard focus survives a page transition.
  • The API caps pageSize, rejects invalid sort fields, and returns a real count.

If your database is Supabase, review the Supabase database documentation for the query and authorization layer. If it is another database, apply the same principle: the pagination UI should reflect the server's actual contract, not assumptions embedded in a component.

What I would measure, and what I would not claim

Measure request duration, response size, error rate, and interaction timing in your own environment. I would not claim a fixed percentage improvement without a controlled benchmark; results vary with indexes, serialization, network distance, cache state, and rendering cost.

Test the first, middle, and last pages, empty and permission-restricted results, slow and failed responses, browser back/forward behavior, and a directly opened URL with pagination parameters.

Which template fits this use case?

Choose a template or starter based on the surrounding capability, not on whether it contains a table example. Inspect its typed list-query boundary, authentication and tenant scoping, invalidation convention, URL state, and deployment path.

If you are comparing implementation foundations, use the SaaS boilerplate decision guide to evaluate those capabilities together. Then browse TanStack templates and look for the template whose routing, data loading, and deployment choices match your product. The decision is which foundation leaves the fewest unowned boundaries around pagination.

Conclusion: a reliable pagination decision

For TanStack Table React Query pagination, keep the table responsible for pagination state and rendering, keep TanStack Query responsible for server data, and make the API return explicit row-count metadata. Use server-side pagination when filters, permissions, or database ownership are involved; use client-side pagination only when the complete dataset is intentionally local.

Next action: compare the SaaS boilerplate options against your required list-query capabilities, then browse the available templates before implementing the table boundary.

FAQ: Should TanStack Table pagination be client-side or server-side?

Use client-side pagination when the full dataset is already loaded and safe to expose to the browser. Use server-side pagination when rows come from a database, filters affect authorization, or the dataset should be loaded incrementally. The table configuration and API contract should make that choice explicit rather than mixing both modes accidentally.

FAQ: How should TanStack Query cache paginated table data?

Put every request variable that changes the response in the query key: page index, page size, filters, sort, tenant scope, and any other server-side parameter. Use keepPreviousData when a stable transition is helpful, but show a fetching indicator so users know the visible rows may represent the previous request.

FAQ: Does a SaaS template need built-in TanStack Table pagination?

Not necessarily. A template is valuable when it provides the boundaries around the table: typed data loading, authentication, URL state, invalidation conventions, and deployment. A component can be added later. Before buying, verify the template's actual architecture and choose the option that supports your query and permission model without hiding important behavior.

Related reading: Tanstack Query V5 Best Practices · Tanstack Query V5 Migration And Best Practices · Tanstack Query V5 Migration And Best Practices 2026

Disclosure and limitations

This article is technical guidance, not a benchmark, security audit, or guarantee of a particular result. Claims are labeled by their basis: implementation examples are calculated or illustrative, documentation references are measured from the linked sources, and environment-specific outcomes are unknown until tested. I have no material connection to the external documentation projects linked here. If you find an error, use the Changelog or contact the author through the about page; corrections should be made against the relevant library and runtime documentation.