Transfer prefetched queries from server-rendered markup to a browser QueryClient.
Server-side rendering
TanStack · Function
Converts a QueryClient cache into a serializable DehydratedState for transferring prefetched data, commonly from server to client. It includes successful queries and paused mutations by default, with options for selection and transformation.
dehydrate converts a QueryClient cache into a plain, serializable DehydratedState containing selected queries and mutations. By default, successful queries and paused mutations are included; options can change inclusion rules and transform data or errors before the result is passed to hydrate.
function dehydrate(client: QueryClient, options?: DehydrateOptions): DehydratedState;| Name | Type | Description |
|---|---|---|
client | QueryClient | The QueryClient whose cache is converted to dehydrated state. |
options | DehydrateOptions | Optional controls for selecting queries and mutations and transforming their data or errors; defaults to an empty options object. |
DehydratedState containing the included dehydrated queries and mutations.
import { QueryClient, dehydrate } from '@tanstack/query-core'
const queryClient = new QueryClient()
await queryClient.prefetchQuery({
queryKey: ['posts'],
queryFn: async () => fetch('/api/posts').then((r) => r.json()),
})
const dehydratedState = dehydrate(queryClient)
console.log(JSON.stringify(dehydratedState))Prefetches posts into a query client and converts its cache into a serializable state suitable for transferring to another environment.
Server-side rendering
State persistence
Custom cache export
dehydrate takes a QueryClient and optional DehydrateOptions, then returns a DehydratedState. The result represents the cache in a plain serializable form for later restoration with hydrate.
Follow-up: How are inclusion and transformation policies selected? The call's options take precedence, then the client's dehydrate defaults, then the library defaults for queries and mutations.
The default output contains dehydrated queries that succeeded and dehydrated mutations that are paused. Other entries require configuration through DehydrateOptions or client defaults.
Follow-up: Why might a failed query be absent from server-rendered state? Because successful queries are the default query inclusion set, so the query must be explicitly selected if failures should be transferred.
A common flow is to prefetch data into a QueryClient, call dehydrate, serialize or embed the resulting state, and later restore it into a client QueryClient with hydrate. This supports server-rendered markup and client startup with prefetched data.
Follow-up: What does the returned state contain? It has mutations and queries collections, whose entries are represented by DehydratedMutation and DehydratedQuery types.
QueryClientDehydrateOptionsDehydratedStateDehydratedQueryDehydratedMutationhydratedefaultShouldDehydrateQuerydefaultShouldDehydrateMutation