Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useHydrate.ts

41 lines1.6 KB

1import { hydrate } from '@tanstack/query-core'
2import { useQueryClient } from './useQueryClient.js'
3import type { HydrateOptions, QueryClient } from '@tanstack/query-core'
4​
5/**
6 * Adds a previously dehydrated `state` into the `queryClient` (from the nearest context, or the one
7 * passed explicitly). If the client already contains data, the new queries will be intelligently merged based
8 * on update timestamp. `HydrationBoundary` wraps this β€” use it directly only if you need to hydrate from your
9 * own component instead.
10 * @param state - The dehydrated state to hydrate into the cache, as produced by `dehydrate`.
11 * @param options - {@link HydrateOptions} to control the hydration.
12 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
13 * be used.
14 * @example
15 * Server-side prefetch handed off to the client via `dehydrate` β€” `dehydratedState` would typically come
16 * from a server load function that prefetched with `queryClient.query` and called `dehydrate(queryClient)`:
17 * ```svelte
18 * <script lang="ts">
19 * import { HydrationBoundary } from '@tanstack/svelte-query'
20 * import type { DehydratedState } from '@tanstack/svelte-query'
21 * import Posts from './Posts.svelte'
22 *
23 * let { dehydratedState }: { dehydratedState: DehydratedState } = $props()
24 * </script>
25 *
26 * <HydrationBoundary state={dehydratedState}>
27 * <Posts />
28 * </HydrationBoundary>
29 * ```
30 */
31export function useHydrate(
32 state?: unknown,
33 options?: HydrateOptions,
34 queryClient?: QueryClient,
35) {
36 const client = useQueryClient(queryClient)
37​
38 if (state) {
39 hydrate(client, state, options)
40 }