|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; |
| 4 | +// We can not useState or useRef in a server component, which is why we are |
| 5 | +// extracting this part out into it's own file with 'use client' on top |
| 6 | +import { useState } from "react"; |
| 7 | + |
| 8 | +function makeQueryClient() { |
| 9 | + return new QueryClient({ |
| 10 | + defaultOptions: { |
| 11 | + queries: { |
| 12 | + // With SSR, we usually want to set some default staleTime |
| 13 | + // above 0 to avoid refetching immediately on the client |
| 14 | + staleTime: 60 * 1000, |
| 15 | + }, |
| 16 | + }, |
| 17 | + }); |
| 18 | +} |
| 19 | + |
| 20 | +let browserQueryClient: QueryClient | undefined = undefined; |
| 21 | + |
| 22 | +function getQueryClient() { |
| 23 | + if (typeof window === "undefined") { |
| 24 | + // Server: always make a new query client |
| 25 | + return makeQueryClient(); |
| 26 | + } |
| 27 | + // Browser: make a new query client if we don't already have one |
| 28 | + // This is very important so we don't re-make a new client if React |
| 29 | + // suspends during the initial render. This may not be needed if we |
| 30 | + // have a suspense boundary BELOW the creation of the query client |
| 31 | + if (!browserQueryClient) browserQueryClient = makeQueryClient(); |
| 32 | + return browserQueryClient; |
| 33 | +} |
| 34 | + |
| 35 | +export default function Providers({ children }: { children: React.ReactNode }) { |
| 36 | + // NOTE: Avoid useState when initializing the query client if you don't |
| 37 | + // have a suspense boundary between this and the code that may |
| 38 | + // suspend because React will throw away the client on the initial |
| 39 | + // render if it suspends and there is no boundary |
| 40 | + const queryClient = getQueryClient(); |
| 41 | + |
| 42 | + return ( |
| 43 | + <QueryClientProvider client={queryClient}>{children}</QueryClientProvider> |
| 44 | + ); |
| 45 | +} |
0 commit comments