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?: unknown
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 const [hydrationQueue, setHydrationQueue] = React.useState<
33 DehydratedState['queries'] | undefined
34 >()
35β
36 const optionsRef = React.useRef(options)
37 optionsRef.current = options
38β
39 // This useMemo is for performance reasons only, everything inside it _must_
40 // be safe to run in every render and code here should be read as "in render".
41 //
42 // This code needs to happen during the render phase, because after initial
43 // SSR, hydration needs to happen _before_ children render. Also, if hydrating
44 // during a transition, we want to hydrate as much as is safe in render so
45 // we can prerender as much as possible.
46 //
47 // For any queries that already exist in the cache, we want to hold back on
48 // hydrating until _after_ the render phase. The reason for this is that during
49 // transitions, we don't want the existing queries and observers to update to
50 // the new data on the current page, only _after_ the transition is committed.
51 // If the transition is aborted, we will have hydrated any _new_ queries, but
52 // we throw away the fresh data for any existing ones to avoid unexpectedly
53 // updating the UI.
54 React.useMemo(() => {
55 if (state) {
56 if (typeof state !== 'object') {
57 return
58 }
59β
60 const queryCache = client.getQueryCache()
61 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
62 const queries = (state as DehydratedState).queries || []
63β
64 const newQueries: DehydratedState['queries'] = []
65 const existingQueries: DehydratedState['queries'] = []
66 for (const dehydratedQuery of queries) {
67 const existingQuery = queryCache.get(dehydratedQuery.queryHash)
68β
69 if (!existingQuery) {
70 newQueries.push(dehydratedQuery)
71 } else {
72 const hydrationIsNewer =
73 dehydratedQuery.state.dataUpdatedAt >
74 existingQuery.state.dataUpdatedAt
75 const queryAlreadyQueued = hydrationQueue?.find(
76 (query) => query.queryHash === dehydratedQuery.queryHash,
77 )
78β
79 if (
80 hydrationIsNewer &&
81 (!queryAlreadyQueued ||
82 dehydratedQuery.state.dataUpdatedAt >
83 queryAlreadyQueued.state.dataUpdatedAt)
84 ) {
85 existingQueries.push(dehydratedQuery)
86 }
87 }
88 }
89β
90 if (newQueries.length > 0) {
91 // It's actually fine to call this with queries/state that already exists
92 // in the cache, or is older. hydrate() is idempotent for queries.
93 hydrate(client, { queries: newQueries }, optionsRef.current)
94 }
95 if (existingQueries.length > 0) {
96 setHydrationQueue((prev) =>
97 prev ? [...prev, ...existingQueries] : existingQueries,
98 )
99 }
100 }
101 }, [client, hydrationQueue, state])
102β
103 React.useEffect(() => {
104 if (hydrationQueue) {
105 hydrate(client, { queries: hydrationQueue }, optionsRef.current)
106 setHydrationQueue(undefined)
107 }
108 }, [client, hydrationQueue])
109β
110 return children as React.ReactElement
111}