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

HydrationBoundary.tsx

107 lines3.6 KB

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