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

HydrationBoundary.tsx

168 lines5.8 KB

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