hydration

· abundance's blog


dehydrate #

dehydrate creates a frozen representation of a cache that can later be hydrated with HydrationBoundary 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.

1import { dehydrate } from '@tanstack/react-query'
2
3const dehydratedState = dehydrate(queryClient, {
4  shouldDehydrateQuery,
5  shouldDehydrateMutation,
6})

Options

Returns

Limitations #

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.:

1// server
2const state = dehydrate(client, { shouldDehydrateQuery: () => true }) // to also include Errors
3const serializedState = mySerialize(state) // transform Error instances to objects
4
5// client
6const state = myDeserialize(serializedState) // transform objects back to Error instances
7hydrate(client, state)

hydrate #

hydrate adds a previously dehydrated state into a cache.

1import { hydrate } from '@tanstack/react-query'
2
3hydrate(queryClient, dehydratedState, options)

Options

Limitations #

If the queries you're trying to hydrate already exist in the queryCache, hydrate will only overwrite them if the data is newer than the data present in the cache. Otherwise, it will not get applied.

HydrationBoundary #

HydrationBoundary 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.

1import { HydrationBoundary } from '@tanstack/react-query'
2
3function App() {
4  return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
5}

Note: Only queries can be dehydrated with an HydrationBoundary.

Options