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

Hydrate.tsx

38 lines1.1 KB

1'use client'
2import * as React from 'react'
3​
4import type { HydrateOptions } from '@tanstack/query-core'
5import { hydrate } from '@tanstack/query-core'
6import { useQueryClient } from './QueryClientProvider'
7import type { ContextOptions } from './types'
8​
9export function useHydrate(
10 state: unknown,
11 options: HydrateOptions & ContextOptions = {},
12) {
13 const queryClient = useQueryClient({ context: options.context })
14​
15 const optionsRef = React.useRef(options)
16 optionsRef.current = options
17​
18 // Running hydrate again with the same queries is safe,
19 // it wont overwrite or initialize existing queries,
20 // relying on useMemo here is only a performance optimization.
21 // hydrate can and should be run *during* render here for SSR to work properly
22 React.useMemo(() => {
23 if (state) {
24 hydrate(queryClient, state, optionsRef.current)
25 }
26 }, [queryClient, state])
28​
29export interface HydrateProps {
30 state?: unknown
31 options?: HydrateOptions
32 children?: React.ReactNode
34​
35export const Hydrate = ({ children, options, state }: HydrateProps) => {
36 useHydrate(state, options)
37 return children as React.ReactElement