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

QueryClientProvider.tsx

69 lines1.8 KB

1import React from 'react'
2​
3import { QueryClient } from '../core'
4​
5declare global {
6 interface Window {
7 ReactQueryClientContext?: React.Context<QueryClient | undefined>
8 }
9}
10​
11const defaultContext = React.createContext<QueryClient | undefined>(undefined)
12const QueryClientSharingContext = React.createContext<boolean>(false)
13​
14// if contextSharing is on, we share the first and at least one
15// instance of the context across the window
16// to ensure that if React Query is used across
17// different bundles or microfrontends they will
18// all use the same **instance** of context, regardless
19// of module scoping.
20function getQueryClientContext(contextSharing: boolean) {
21 if (contextSharing && typeof window !== 'undefined') {
22 if (!window.ReactQueryClientContext) {
23 window.ReactQueryClientContext = defaultContext
24 }
25​
26 return window.ReactQueryClientContext
27 }
28​
29 return defaultContext
31​
32export const useQueryClient = () => {
33 const queryClient = React.useContext(
34 getQueryClientContext(React.useContext(QueryClientSharingContext))
35 )
36​
37 if (!queryClient) {
38 throw new Error('No QueryClient set, use QueryClientProvider to set one')
39 }
40​
41 return queryClient
43​
44export interface QueryClientProviderProps {
45 client: QueryClient
46 contextSharing?: boolean
47 children?: React.ReactNode
49​
50export const QueryClientProvider = ({
51 client,
52 contextSharing = false,
53 children,
54}: QueryClientProviderProps): JSX.Element => {
55 React.useEffect(() => {
56 client.mount()
57 return () => {
58 client.unmount()
59 }
60 }, [client])
61​
62 const Context = getQueryClientContext(contextSharing)
63​
64 return (
65 <QueryClientSharingContext.Provider value={contextSharing}>
66 <Context.Provider value={client}>{children}</Context.Provider>
67 </QueryClientSharingContext.Provider>
68 )