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

QueryClientProvider.tsx

68 lines1.7 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
48​
49export const QueryClientProvider: React.FC<QueryClientProviderProps> = ({
50 client,
51 contextSharing = false,
52 children,
53}) => {
54 React.useEffect(() => {
55 client.mount()
56 return () => {
57 client.unmount()
58 }
59 }, [client])
60​
61 const Context = getQueryClientContext(contextSharing)
62​
63 return (
64 <QueryClientSharingContext.Provider value={contextSharing}>
65 <Context.Provider value={client}>{children}</Context.Provider>
66 </QueryClientSharingContext.Provider>
67 )