Open History to see the last commit
1'use client'
2import * as React from 'react'
3β
4import { hydrate } from '@tanstack/query-core'
5import { useQueryClient } from './QueryClientProvider'
6import type {
7 DehydratedState,
8 HydrateOptions,
9 OmitKeyof,
10 QueryClient,
11} from '@tanstack/query-core'
12β
13export interface HydrationBoundaryProps {
14 state: DehydratedState | null | undefined
15 options?: OmitKeyof<HydrateOptions, 'defaultOptions'> & {
16 defaultOptions?: OmitKeyof<
17 Exclude<HydrateOptions['defaultOptions'], undefined>,
18 'mutations'
19 >
20 }
21 children?: React.ReactNode
22 queryClient?: QueryClient
23}
24β
25export const HydrationBoundary = ({
26 children,
27 options = {},
28 state,
29 queryClient,
30}: HydrationBoundaryProps) => {
31 const client = useQueryClient(queryClient)
32β
33 const optionsRef = React.useRef(options)
34 optionsRef.current = options
35β
36 // This useMemo is for performance reasons only, everything inside it must
37 // be safe to run in every render and code here should be read as "in render".
38 //
39 // This code needs to happen during the render phase, because after initial
40 // SSR, hydration needs to happen _before_ children render. Also, if hydrating
41 // during a transition, we want to hydrate as much as is safe in render so
42 // we can prerender as much as possible.
43 //
44 // For any queries that already exist in the cache, we want to hold back on
45 // hydrating until _after_ the render phase. The reason for this is that during
46 // transitions, we don't want the existing queries and observers to update to
47 // the new data on the current page, only _after_ the transition is committed.
48 // If the transition is aborted, we will have hydrated any _new_ queries, but
49 // we throw away the fresh data for any existing ones to avoid unexpectedly
50 // updating the UI.
51 const hydrationQueue: DehydratedState['queries'] | undefined =
52 React.useMemo(() => {
53 if (state) {
54 if (typeof state !== 'object') {
55 return
56 }
57β
58 const queryCache = client.getQueryCache()
59 // State is supplied from the outside and we might as well fail
60 // gracefully if it has the wrong shape, so while we type `queries`
61 // as required, we still provide a fallback.
62 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
63 const queries = state.queries || []
64β
65 const newQueries: DehydratedState['queries'] = []
66 const existingQueries: DehydratedState['queries'] = []
67 for (const dehydratedQuery of queries) {
68 const existingQuery = queryCache.get(dehydratedQuery.queryHash)
69β
70 if (!existingQuery) {
71 newQueries.push(dehydratedQuery)
72 } else {
73 const hydrationIsNewer =
74 dehydratedQuery.state.dataUpdatedAt >
75 existingQuery.state.dataUpdatedAt ||
76 (dehydratedQuery.promise &&
77 existingQuery.state.status !== 'pending' &&
78 existingQuery.state.fetchStatus !== 'fetching' &&
79 dehydratedQuery.dehydratedAt !== undefined &&
80 dehydratedQuery.dehydratedAt >
81 existingQuery.state.dataUpdatedAt)
82β
83 if (hydrationIsNewer) {
84 existingQueries.push(dehydratedQuery)
85 }
86 }
87 }
88β
89 if (newQueries.length > 0) {
90 // It's actually fine to call this with queries/state that already exists
91 // in the cache, or is older. hydrate() is idempotent for queries.
92 hydrate(client, { queries: newQueries }, optionsRef.current)
93 }
94 if (existingQueries.length > 0) {
95 return existingQueries
96 }
97 }
98 return undefined
99 }, [client, state])
100β
101 React.useEffect(() => {
102 if (hydrationQueue) {
103 hydrate(client, { queries: hydrationQueue }, optionsRef.current)
104 }
105 }, [client, hydrationQueue])
106β
107 return children as React.ReactElement
108}