Transfer prefetched data from server to browser
Server-rendered applications
TanStack · Function
Restores a dehydrated TanStack Query cache snapshot into a QueryClient, commonly transferring prefetched server data to the client. Existing entries are updated only when the incoming data is newer.
hydrate restores a dehydrated cache snapshot into a QueryClient. It creates missing queries, updates existing ones only when the incoming data is newer, resets newly created queries to an idle fetch status, and can resume an in-flight promise instead of invoking the query function again.
function hydrate(
client: QueryClient,
dehydratedState: Partial<DehydratedState>,
options?: HydrateOptions,
): void;| Name | Type | Description |
|---|---|---|
client | QueryClient | The QueryClient whose cache will be restored. |
dehydratedState | Partial<DehydratedState> | A partial dehydrated cache state, typically produced by dehydrate. |
options | HydrateOptions | Optional hydration settings, including merged defaults and data deserialization. |
void
hydrate to restore a cache snapshot created by dehydrate into a client-side QueryClient.import { QueryClient, dehydrate, hydrate } from '@tanstack/query-core'
const serverClient = new QueryClient()
await serverClient.prefetchQuery({
queryKey: ['posts'],
queryFn: async () => [{ id: 1, title: 'Hello' }],
})
const dehydratedState = dehydrate(serverClient)
const browserClient = new QueryClient()
hydrate(browserClient, dehydratedState)Prefetch data into one client, serialize its cache, then restore that state into a client used by the browser.
Server-rendered applications
Persisted or serialized cache state
Custom serialization pipelines
hydrate?hydrate takes a QueryClient, a partial DehydratedState, and optional HydrateOptions, then returns void. It restores the snapshot into the client's cache, commonly after server-side prefetching and dehydration.
Follow-up: What happens when a matching query already exists? The hydrated data is applied only if it is newer than the cached data.
hydrate handle queries that are not already cached?Missing queries are built from the dehydrated snapshot. Their fetch status is reset to idle, preventing a newly restored query from remaining stuck in a fetching state.
Follow-up: How are in-flight requests handled? An in-flight dehydrated promise is resumed through query.fetch() and reused as the initial promise.
HydrateOptions customize?HydrateOptions can provide defaults merged into every restored query and mutation, in addition to the client's hydration defaults. It can also provide deserializeData to reverse a serialization step.
Follow-up: Why is deserialization needed? Serialized server data must be converted back into the runtime representation expected by the client cache.
dehydrateQueryClientDehydratedStateHydrateOptions