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