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

useHydrate.ts

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