dehydrate creates a frozen representation of a cache that can later be hydrated with Hydrate, useHydrate, or hydrate. This is useful for passing prefetched queries from server to client or persisting queries to localStorage or other persistent locations. It only includes currently successful queries by default.
import { dehydrate } from '@tanstack/react-query'
const dehydratedState = dehydrate(queryClient, {
shouldDehydrateQuery,
})
import { dehydrate } from '@tanstack/react-query'
const dehydratedState = dehydrate(queryClient, {
shouldDehydrateQuery,
})
Options
Returns
Some storage systems (such as browser Web Storage API) require values to be JSON serializable. If you need to dehydrate values that are not automatically serializable to JSON (like Error or undefined), you have to serialize them for yourself. Since only successful queries are included per default, to also include Errors, you have to provide shouldDehydrateQuery, e.g.:
// server
const state = dehydrate(client, { shouldDehydrateQuery: () => true }) // to also include Errors
const serializedState = mySerialize(state) // transform Error instances to objects
// client
const state = myDeserialize(serializedState) // transform objects back to Error instances
hydrate(client, state)
// server
const state = dehydrate(client, { shouldDehydrateQuery: () => true }) // to also include Errors
const serializedState = mySerialize(state) // transform Error instances to objects
// client
const state = myDeserialize(serializedState) // transform objects back to Error instances
hydrate(client, state)
hydrate adds a previously dehydrated state into a cache.
import { hydrate } from '@tanstack/react-query'
hydrate(queryClient, dehydratedState, options)
import { hydrate } from '@tanstack/react-query'
hydrate(queryClient, dehydratedState, options)
Options
If the queries included in dehydration already exist in the queryCache, hydrate does not overwrite them and they will be silently discarded.
useHydrate adds a previously dehydrated state into the queryClient that would be returned by useQueryClient(). If the client already contains data, the new queries will be intelligently merged based on update timestamp.
import { useHydrate } from '@tanstack/react-query'
useHydrate(dehydratedState, options)
import { useHydrate } from '@tanstack/react-query'
useHydrate(dehydratedState, options)
Options
Hydrate wraps useHydrate into component. Can be useful when you need hydrate in class component or need hydrate on same level where QueryClientProvider rendered.
import { Hydrate } from '@tanstack/react-query'
function App() {
return <Hydrate state={dehydratedState}>...</Hydrate>
}
import { Hydrate } from '@tanstack/react-query'
function App() {
return <Hydrate state={dehydratedState}>...</Hydrate>
}
Options