Server data
Tables, lists and comboboxes over any backend: one contract for paging, one schema for filters, adapters and serializers for each wire format.
Four layers, no backend assumed
- A PageSource is the contract:
fetchPage(request, { signal })returns rows and whatever the backend knows (a total, an estimate,hasMore, cursors). An adapter per wire format builds one from yourrequestfunction; none of them fetches by itself or depends on a backend library. - A filter schema declares the filters once. It types the values, drives the filter UIs, keeps them in the URL, and is the whitelist the serializers check every field against.
- Server data hooks run on TanStack Query, which never shows in their types: previous rows stay while the next page loads, superseded requests are aborted, a 4xx is never retried.
- Components: ServerDataTable, ServerList and ServerCombobox, with the filter UIs FilterSearch, FilterChips and FilterPanel.
ServerDataTable brings the filter schema and the PageSource contract. The adapter for your backend's paging and the serializer for its query language are items of their own, so add only the ones it speaks: here a Spring controller that reads an RSQL filter. The tables below name the item for each.
Pagination styles
| Style | The table shows | Good at | Costs | Adapter | Item |
|---|---|---|---|---|---|
| Page and size, limit and offset | Page numbers, Showing 21–40 of 312 | Jump to any page; easy to cache and share | Rows drift when others insert; a COUNT per query; deep pages are slow | pagedSource({ base }), offsetSource | page-source-rest |
| Cursor or keyset | Load more, or infinite | Stable and fast at any depth | No jump to page N; needs a unique, ordered key | cursorSource (opaque, or keyset) | page-source-cursor |
| Relay | Load more, or previous and next | Cursors plus pageInfo and an optional totalCount | Same as cursors | relaySource | page-source-relay |
| Link header (RFC 8288) | Previous and next, about N from last | Navigation the server already wrote | A total only on the last page | linkHeaderSource | page-source-link |
| Spring Page and Slice | Page numbers (Page), previous and next (Slice) | Pageable controllers as they are | Page runs a count query; Slice has no total | springPageSource, springSliceSource | page-source-spring |
Navigation follows what the source gives (navigation="auto"); pass pages, prev-next, load-more or infinite to choose. A source's fetchTotal runs as its own cached query, so a slow count never holds back the rows.
| The source gives | The UI shows |
|---|---|
| An exact total (or fetchTotal) | Page numbers and Showing 21–40 of 312 |
| totalEstimate | Previous and next, Showing 21–40 of about 300 |
| Only hasMore | Previous and next, Showing 21–40 |
| A cursor | Load more, or infinite with navigation="infinite" |
Wire formats
| Format | Grammar | Spoken by | Serializer | Notes | Item |
|---|---|---|---|---|---|
| Flat params (DTO, suffix, bracket) | and only | A request DTO, json-server, Django filters | queryParams | URL-friendly; refuses or | filter-schema |
| RSQL / FIQL | and, or, nesting | rsql-jpa-specification, many Java and .NET APIs | rsql | Compact; quoted, escaped arguments | filter-rsql |
| OData $filter | the full grammar | ASP.NET OData, SAP, Dynamics | odata | Verbose; dates unquoted | filter-odata |
| Spring Filter | and, or, not | turkraft/springfilter | springFilter | Java only; refuses wildcards in text | filter-spring |
| JSON AST | the full grammar | A POST body for any backend | jsonAst | Safest: nothing to escape | filter-schema |
| GraphQL where | typed, nested | Hasura, Prisma | graphqlWhere | Goes in variables, never in the query | filter-graphql |
| q only | free text | A search endpoint | searchOnly | Ignores every other field | filter-schema |
- Field names come only from the schema, never from what someone types, and every serializer checks them again.
- Each serializer escapes per its grammar (RSQL and Spring Filter backslashes, OData doubled quotes, LIKE escapes for Hasura) or throws a
FilterSerializeErrorfor a value it can't write safely, like a wildcard inside a text match. The table then shows its error state instead of sending a broken query. - Dates go out as ISO 8601 unless you pass
dates: "iso-date" | "epoch-ms" | fn; strings,Dateand Temporal values all work. A date range's end is inclusive:ltethe last day, orend: "next-day"forltthe day after when the backend stores date-times.
Latency and errors
arraySource pages an array in memory with delay and fail, for demos, tests and mockups. Page through this table, then switch failures on: the previous rows stay while a page loads, the status says "Loading…" only past 400 ms, and an error offers a retry instead of an empty table.
| Status | ||||
|---|---|---|---|---|
One table, three backends
The same tasks behind a page-and-size API with a total, keyset cursors and a Spring Page. Filter, sort and page, and watch the request each adapter sends and the filter in every wire format.
| Status | |||
|---|---|---|---|
The URL
urlState takes hashUrlState(), historyUrlState() or your router wrapped in the same three methods. The URL keeps schema values, not the wire format, in readable params, and falls back to one encoded f param when a filter has or groups. Writes replace the entry by default; history: "push-page" adds one per page so Back steps through them.
Hooks and mutations
The hooks use your app's QueryClient when it has one, and a shared default otherwise. DataProvider provides the registry's defaults: two retries except on a 4xx, read from the error's status (readJson throws an HttpError with it), 30 s fresh, no refetch on focus. Mount one per request when rendering on a server.
Resources that aren't paged
useServerQuery(key, fetch, options) loads one resource and returns what the page hooks return, with data in place of the rows: status, fetching, previous, error and retry. fetch gets the signal, aborted when the key changes or the component unmounts. It takes enabled, staleTime, placeholder and keepPrevious (off by default, so a detail never shows another id's data). On a server it renders pending, or the data the request's client already holds.
settleItems(items, result, variables)maps each page's rows, in page and infinite queries; totals stay.settle(result, variables, current, queryKey)writes eachuseServerQueryunder the key, andundefinedleaves one alone.- On success they cancel the read in flight of each query they write, so an answer sent before the change can't overwrite it, and request nothing. The other queries under the key are marked stale and reload when next shown; one that was already loading starts again. They reach every cached query under the key, mounted or not, as one filled with
setQueryData. A failed mutation still rolls backoptimisticrows and refreshes the key, unlessrefreshOnError: falsesays the failure changed nothing. useInvalidateSource(source)resolves once the shown queries have reloaded, failed or not;{ throwOnError: true }, on the hook or on one call, rejects with the error instead.- Every reload these hooks make (
useInvalidateSource, a mutation's refresh after success or failure, and the restart aftersettle) starts again any read under the key that is in flight, its first load included, since it may have left before the write and answer with the data from before it. The old request's signal aborts, the query stays pending or fetching without an error, and whatever that request resolves or rejects with later is dropped. TanStack's owninvalidateQueriesjoins a first load in flight instead, so invalidate through the hooks.
Writing a change the app learned of elsewhere
When the server tells the app what changed outside a mutation (a push event, a socket message, another request's answer), usePatchSource(source) returns patch(changes, options), which writes it into every cached query under the key, mounted or not, without a request. changes.items(rows) maps the rows of each page and infinite list (totals stay), and changes.resource(current, queryKey) each other query, undefined leaving one alone. patchSource(client, source, changes, options) does the same outside React.
- A read in flight under the key left before the change and could answer with the data from before it. So each read whose query the patch writes, and each first read (no data yet, so nothing to patch), is cancelled silently and started again in the same batch, with or without
refetch: the number of requests stays the same, nothing is left pending, and the old request's answer orAbortErroris dropped. A read of a query the patch leaves alone goes on. { inFlight: "cancel" }cancels the read of each query the patch writes instead of starting it again: the query keeps the patch and stops fetching, as after a mutation'ssettle, with no mutation. The read's late answer is dropped and nothing shows an error. A first read the patch writes nothing into still starts again, since its query would otherwise stay pending."restart"is the default.{ awaitRestarted: true }resolves once every read the patch started again has settled, following each query through later restarts (another patch, an invalidation) to its latest read, and starts no read of its own. WiththrowOnErrorit rejects with the first failure, after retries; an aborted read never counts, and a laterinFlight: "cancel"patch settles it with the data it wrote. It is the way to know a restarted read failed without the extra readrefetchmakes, for a resource whose every read overwrites per-item ETags. Awaiting the query'spromiseinstead rejects with a silentCancelledErrorwhenever another write restarts the read.{ refetch: true }reloads the whole key afterwards, asuseInvalidateSourcedoes, and the promise resolves once the shown queries have reloaded (throwOnErrorrejects on a failed reload). That reload restarts every read in flight under the key, so the patch leaves the restart to it rather than sending a request that is aborted at once. By default nothing new is requested and the patched queries count as fresh.- The call resolves with what it did, as lists of query keys in the cache's order:
written, the queries it wrote;cancelled, those whose read it stopped (inFlight: "cancel");restarted, those whose read it started again (a written query's under"restart", a first read it left empty, which restarts under"cancel"too, and withrefetchevery read that was in flight under the key); andrefetched, those therefetchreload read that weren't reading. A cancelled query that is shown is read again byrefetch, so it is in both. A read ran again whenrestartedorrefetchedisn't empty.awaitRestartedwaits for exactly therestartedreads. A caller that ignores the result works as before. - A patch is what the server holds now. For a change the server hasn't confirmed yet, use
useSourceMutation'soptimistic, which rolls back on failure.
Cancel now, write later
A screen that fetches the answer itself, with another request than the query's on a first load, must stop the reads in flight before it waits, or one of them lands while it does. useHoldSource(source) returns a function that begins a hold (holdSource(client, source) outside React). The hold cancels every read in flight under the key at once and pauses the hooks' reads under it until it ends: hold.patch(changes, options) writes the answer and ends it, and hold.release() ends it without writing.
- A paused read shows as fetching and sends nothing. A read the hold cancelled waits as one, so a first load stays pending and fetching, never pending and idle. A read a mount, a focus or reconnect refetch, a
retryor an invalidation starts during the hold waits too, deduplicated as TanStack does. hold.patchispatchwithinFlight: "cancel": each query it writes keeps the answer and its paused read is dropped without a request, so a first load gets its first value from the caller. Every other paused read runs then, and is listed inrestarted.refetch,awaitRestartedandthrowOnErrorwork as onpatch, after the hold has ended, so the reload isn't paused.hold.release(), after the caller's fetch failed, lets every paused read run, each once: a first load reads with its own query function and nothing stays pending. It does nothing once the hold has ended. The hook releases the holds its component began when it unmounts. Apatchafter the hold ended still writes, as a cancelling patch.- Holds nest and overlap: a read waits until every hold over its key has ended. A read the hooks don't own (a
prefetchQuery) can't wait: the hold cancels it and starts it again when it ends, unless its patch writes that query.hold.cancelledlists the reads it stopped. - The hold adds no request: the reads it cancels or pauses either get the caller's answer or run once when it ends, as they would have. Only a read already in flight when the hold begins and that it lets run afterwards is sent twice, the first time aborted.
Reloading on focus, reconnect and mount
refetchOnWindowFocus, refetchOnReconnect and refetchOnMount decide when a query reloads on its own: true when it is stale, "always" even when it is fresh, false never. createDataClient sets the app's defaults (no reload on focus; a stale query reloads on mount, and on reconnect unless networkMode is "always", as in TanStack), and useServerQuery, defineResource, useServerResource, useServerPage, useServerInfinite and useServerTotal take their own. On useServerResource the call's option wins over the definition's, and a page's total follows its page.
Never reload a resource whose reads overwrite per-item ETags (or versions) that a later write sends back: a read on focus or reconnect while a person edits a row hands them the ETag of a version they never saw, and the save that should have failed with a conflict overwrites it. Set refetchOnWindowFocus: false and refetchOnReconnect: false on its defineResource, since TanStack reloads a query when any hook that reads it asks to, and write each save's answer with settle or patch.
Shared and seeded resources
When two screens read the same resource, declare it once with defineResource (its key, fetch, staleTime and seeds) and read it with useServerResource(resource, params, options). When one answer contains another resource, seeds writes it: after the fetch resolves, unless it was aborted, whether or not that resource is mounted, and never over data written after the fetch started. select picks what data holds, typed as its result, recomputed only when the answer changes and kept by identity when equal; the cache, settle and seeds still see the whole answer.
Typed errors
error is unknown by default, since a fetch can reject with anything. Register a defaultError with TanStack Query to type it across the app, or pass the error type after the data type; useServerPage, useServerInfinite, useServerTotal and useSourceMutation take it too.
Retries
createDataClient({ retry, retryDelay }): a number of retries keeps the 4xx rule, a function (failures, error) => boolean decides alone. The default stays two retries for anything without a 4xx status, because fetch reports a dropped connection as a TypeError with no status. When your errors carry no status (IPC, a domain error, a parse error), retrying only isTransientError fails them at once instead of after the backoff. retry: false never retries, as 0 does. Mutations never retry: a write that failed may still have reached the server.
Offline and network mode
TanStack Query's default networkMode, "online", pauses every read and write after the browser fires offline, until it fires online: a read stays pending, never reaching its error state, and a write waits. When the backend is local (Electron IPC, a server on localhost) or the app shows its own offline UI, use "always", on createDataClient for every query and mutation or on one hook: useServerQuery, defineResource and useServerResource, useServerPage, useServerInfinite, useServerTotal and useSourceMutation take networkMode. "offlineFirst" runs the first attempt and pauses only the retries, for a service worker cache. With "always", a stale query no longer reloads when the browser comes back online, as in TanStack; refetchOnReconnect: true keeps it.
Polling
refetchInterval reloads a query every so many ms while it's shown, on useServerQuery, useServerResource, useServerPage and useServerInfinite, and on ServerDataTable and ServerList. A function of the hook's state decides again after every render and stops the polling once it returns false, so a screen that waits for a login or a job asks only while the answer is pending.
- The next poll is counted from when the last read settled, so a slow server never gets two requests at once, and any other read of the query (a mutation's refresh, a patch) pushes it back. A hold pauses it like any read.
- It stops while the document is hidden, and once it's visible again reloads at once when an interval went by.
refetchIntervalInBackgroundkeeps it going. - A poll is a background refresh: the data stays,
fetchingandpollingare true andstatusstayssuccess. A failed poll follows the retry rules and keeps the last data beside the error. The table and list don't mark their rows busy or say "Loading…" for a poll; leavepollingout of your own status the same way. - Screens that read the same key share one timer, at the shortest interval any of them asks for, and it stops when the last one unmounts or moves to another key. With polling off the hooks set no timer.
Mutations one at a time
Mutations with the same scope: { id }, from one useSourceMutation or several, run one at a time in the order they were called: the next starts once the one before has settled, its refresh included (write the answer with settle or settleItems to skip the reload between them). A failure doesn't stop the queue. To stop at the first one, have onError raise a flag that mutationFn reads: a step's mutationFn runs only after the step before has settled. mutationKey finds them with useMutationState or client.isMutating. Different scopes, or none, run side by side.
Testing
Query results reach React through TanStack Query's notifyManager, which schedules them with setTimeout(0). So when a test awaits one act() around a source settling, the query is done but the component still shows the state before it. Set the scheduler to queueMicrotask in your test setup, or wait with findBy… and waitFor. An arraySource with delay and fail stands in for the backend, and a client with retry: 0 shows an error at once.
Effect
There is no Effect dependency: run a program to a Promise and pass the signal, so a superseded request interrupts its fiber.
Accessibility and agents
- A polite status says what is shown after each load, but not after a poll; focus stays on the control you pressed.
- Row navigation starts again at the first row without moving focus; new rows never take it.
- Agents sort and page through the table's own actions and filter by label through its filters group:
filter("Status", ["Open"]).