Open History to see the last commit
1import { hydrate } from '@tanstack/query-core'
2import { Fragment } from 'preact'
3import { useEffect, useMemo, useRef } from 'preact/hooks'
4import { useQueryClient } from './QueryClientProvider'
5import type {
6 DehydratedState,
7 HydrateOptions,
8 OmitKeyof,
9 QueryClient,
10} from '@tanstack/query-core'
11import type { ComponentChildren } from 'preact'
12β
13/**
14 * The props accepted by `HydrationBoundary`.
15 */
16export interface HydrationBoundaryProps {
17 /**
18 * The state to hydrate.
19 */
20 state: DehydratedState | null | undefined
21 /**
22 * Optional. Note: unlike `hydrate`, `mutations` cannot be set here.
23 */
24 options?: OmitKeyof<HydrateOptions, 'defaultOptions'> & {
25 defaultOptions?: OmitKeyof<
26 Exclude<HydrateOptions['defaultOptions'], undefined>,
27 'mutations'
28 >
29 }
30 /**
31 * The components to render β always rendered unconditionally, not gated on hydration. New queries are
32 * hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated
33 * data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it
34 * lands.
35 */
36 children?: ComponentChildren
37 /**
38 * Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used.
39 */
40 queryClient?: QueryClient
41}
42β
43/**
44 * `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by
45 * `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on
46 * update timestamp.
47 *
48 * Note: Only `queries` can be dehydrated with an `HydrationBoundary`.
49 * @param props - The dehydrated `state` to hydrate, the hydrate `options`, an optional custom
50 * `queryClient`, and the `children` to render.
51 * @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the
52 * cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect
53 * after commit.
54 * @example
55 * ```tsx
56 * import { HydrationBoundary } from '@tanstack/preact-query'
57 *
58 * function App() {
59 * return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
60 * }
61 * ```
62 * @example
63 * Server-side prefetch handed off to the client via `dehydrate`:
64 * ```tsx
65 * import { HydrationBoundary, dehydrate, noop } from '@tanstack/preact-query'
66 *
67 * async function ServerComponent() {
68 * const queryClient = getQueryClient()
69 *
70 * await queryClient
71 * .query({
72 * queryKey: ['posts'],
73 * queryFn: fetchPosts,
74 * })
75 * .catch(noop)
76 *
77 * return (
78 * <HydrationBoundary state={dehydrate(queryClient)}>
79 * <Posts />
80 * </HydrationBoundary>
81 * )
82 * }
83 * ```
84 */
85export const HydrationBoundary = ({
86 children,
87 options = {},
88 state,
89 queryClient,
90}: HydrationBoundaryProps) => {
91 const client = useQueryClient(queryClient)
92β
93 const optionsRef = useRef(options)
94 useEffect(() => {
95 optionsRef.current = options
96 })
97β
98 // This useMemo is for performance reasons only, everything inside it must
99 // be safe to run in every render and code here should be read as "in render".
100 //
101 // This code needs to happen during the render phase, because after initial
102 // SSR, hydration needs to happen _before_ children render. Also, if hydrating
103 // during a transition, we want to hydrate as much as is safe in render so
104 // we can prerender as much as possible.
105 //
106 // For any queries that already exist in the cache, we want to hold back on
107 // hydrating until _after_ the render phase. The reason for this is that during
108 // transitions, we don't want the existing queries and observers to update to
109 // the new data on the current page, only _after_ the transition is committed.
110 // If the transition is aborted, we will have hydrated any _new_ queries, but
111 // we throw away the fresh data for any existing ones to avoid unexpectedly
112 // updating the UI.
113 const hydrationQueue: DehydratedState['queries'] | undefined = useMemo(() => {
114 if (state) {
115 if (typeof state !== 'object') {
116 return
117 }
118β
119 const queryCache = client.getQueryCache()
120 // State is supplied from the outside and we might as well fail
121 // gracefully if it has the wrong shape, so while we type `queries`
122 // as required, we still provide a fallback.
123 // oxlint-disable-next-line typescript/no-unnecessary-condition
124 const queries = state.queries || []
125β
126 const newQueries: DehydratedState['queries'] = []
127 const existingQueries: DehydratedState['queries'] = []
128 for (const dehydratedQuery of queries) {
129 const existingQuery = queryCache.get(dehydratedQuery.queryHash)
130β
131 if (!existingQuery) {
132 newQueries.push(dehydratedQuery)
133 } else {
134 const hydrationIsNewer =
135 dehydratedQuery.state.dataUpdatedAt >
136 existingQuery.state.dataUpdatedAt ||
137 (dehydratedQuery.promise &&
138 existingQuery.state.status !== 'pending' &&
139 existingQuery.state.fetchStatus !== 'fetching' &&
140 dehydratedQuery.dehydratedAt > existingQuery.state.dataUpdatedAt)
141β
142 if (hydrationIsNewer) {
143 existingQueries.push(dehydratedQuery)
144 }
145 }
146 }
147β
148 if (newQueries.length > 0) {
149 // It's actually fine to call this with queries/state that already exists
150 // in the cache, or is older. hydrate() is idempotent for queries.
151 hydrate(client, { queries: newQueries }, optionsRef.current)
152 }
153 if (existingQueries.length > 0) {
154 return existingQueries
155 }
156 }
157 return undefined
158 }, [client, state])
159β
160 useEffect(() => {
161 if (hydrationQueue) {
162 hydrate(client, { queries: hydrationQueue }, optionsRef.current)
163 }
164 }, [client, hydrationQueue])
165β
166 return <Fragment>{children}</Fragment>
167}