TanStackT
TanStack2y ago
8 replies
homeless-violet

Use my queryClient oustide React context

Hey there, I'm here because I'm not sure of how it would work to use my queryClient both inside & outside my react context. Let me explain:
Suppose I have this file:
const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            staleTime: 1000,
            gcTime: 1000 * 60 * 60 * 24,
            networkMode: "always",
            retry: 3,
        },
    },
})

export const QueryClientProvider = ({ children }: PropsWithChildren) => {
    useEffect(() => {
        initReactQueries(queryClient)
    }, [])

    return (
        <PersistQueryClientProvider
            client={queryClient}
            persistOptions={{ persister: dataStoragePersister }}
        >
            {children}
        </PersistQueryClientProvider>
    )
}


Where my dataStoragePersister is defined oustide (and does work). If I export my queryClient variable and use it somewhere else (for exemple in an axios interceptor or in a simple function somewhere), does it will use the persister ? Or I must use the client by using useQueryClient to access it version with the persister ? I guess my real questions are:
- Does the queryClient is a singleton that is altered by the PersistQueryClientProvider, or does it copy and manage it own instance of the client ?
- Using the client outstide the react context (and so without useQueryClient) could lead to unexpected behavior ? Like trying to trigger a query when the persister is not yet up or anything else ?

Because it would be really usefull to use it sometimes outside of my react components, for Axios at least.

Thanks !
Was this page helpful?