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

providers.tsx

39 lines1.5 KB

1// In Next.js, this file would be called: app/providers.tsx
2'use client'
3​
4// Since QueryClientProvider relies on useContext under the hood, we have to put 'use client' on top
5import { QueryClientProvider, environmentManager } from '@tanstack/react-query'
6import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
7import { makeQueryClient } from '@/app/make-query-client'
8import type { QueryClient } from '@tanstack/react-query'
9​
10let browserQueryClient: QueryClient | undefined = undefined
11​
12function getQueryClient() {
13 if (environmentManager.isServer()) {
14 // Server: always make a new query client
15 return makeQueryClient()
16 } else {
17 // Browser: make a new query client if we don't already have one
18 // This is very important, so we don't re-make a new client if React
19 // suspends during the initial render. This may not be needed if we
20 // have a suspense boundary BELOW the creation of the query client
21 if (!browserQueryClient) browserQueryClient = makeQueryClient()
22 return browserQueryClient
23 }
25​
26export default function Providers({ children }: { children: React.ReactNode }) {
27 // NOTE: Avoid useState when initializing the query client if you don't
28 // have a suspense boundary between this and the code that may
29 // suspend because React will throw away the client on the initial
30 // render if it suspends and there is no boundary
31 const queryClient = getQueryClient()
32​
33 return (
34 <QueryClientProvider client={queryClient}>
35 {children}
36 <ReactQueryDevtools />
37 </QueryClientProvider>
38 )