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

QueryClientProvider.tsx

99 lines2.7 KB

1'use client'
2import * as React from 'react'
3​
4import type { QueryClient } from '@tanstack/query-core'
5import type { ContextOptions } from './types'
6​
7declare global {
8 interface Window {
9 ReactQueryClientContext?: React.Context<QueryClient | undefined>
10 }
12​
13export const defaultContext = React.createContext<QueryClient | undefined>(
14 undefined,
16const QueryClientSharingContext = React.createContext<boolean>(false)
17​
18// If we are given a context, we will use it.
19// Otherwise, if contextSharing is on, we share the first and at least one
20// instance of the context across the window
21// to ensure that if React Query is used across
22// different bundles or microfrontends they will
23// all use the same **instance** of context, regardless
24// of module scoping.
25function getQueryClientContext(
26 context: React.Context<QueryClient | undefined> | undefined,
27 contextSharing: boolean,
28) {
29 if (context) {
30 return context
31 }
32 if (contextSharing && typeof window !== 'undefined') {
33 if (!window.ReactQueryClientContext) {
34 window.ReactQueryClientContext = defaultContext
35 }
36​
37 return window.ReactQueryClientContext
38 }
39​
40 return defaultContext
42​
43export const useQueryClient = ({ context }: ContextOptions = {}) => {
44 const queryClient = React.useContext(
45 getQueryClientContext(context, React.useContext(QueryClientSharingContext)),
46 )
47​
48 if (!queryClient) {
49 throw new Error('No QueryClient set, use QueryClientProvider to set one')
50 }
51​
52 return queryClient
54​
55type QueryClientProviderPropsBase = {
56 client: QueryClient
57 children?: React.ReactNode
59type QueryClientProviderPropsWithContext = ContextOptions & {
60 contextSharing?: never
61} & QueryClientProviderPropsBase
62type QueryClientProviderPropsWithContextSharing = {
63 context?: never
64 contextSharing?: boolean
65} & QueryClientProviderPropsBase
66​
67export type QueryClientProviderProps =
68 | QueryClientProviderPropsWithContext
69 | QueryClientProviderPropsWithContextSharing
70​
71export const QueryClientProvider = ({
72 client,
73 children,
74 context,
75 contextSharing = false,
76}: QueryClientProviderProps): React.JSX.Element => {
77 React.useEffect(() => {
78 client.mount()
79 return () => {
80 client.unmount()
81 }
82 }, [client])
83​
84 if (process.env.NODE_ENV !== 'production' && contextSharing) {
85 client
86 .getLogger()
87 .error(
88 `The contextSharing option has been deprecated and will be removed in the next major version`,
89 )
90 }
91​
92 const Context = getQueryClientContext(context, contextSharing)
93​
94 return (
95 <QueryClientSharingContext.Provider value={!context && contextSharing}>
96 <Context.Provider value={client}>{children}</Context.Provider>
97 </QueryClientSharingContext.Provider>
98 )