From 85e9a6edd4d90556c764c0d741216c83e4fdcb49 Mon Sep 17 00:00:00 2001 From: Alexander Grattan Date: Fri, 26 Jul 2024 13:10:52 -0400 Subject: [PATCH] feat: update react query provider to be in-line with docs --- apps/client/src/utils/query-provider.tsx | 41 ++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/apps/client/src/utils/query-provider.tsx b/apps/client/src/utils/query-provider.tsx index d0f3a745..24fbd242 100644 --- a/apps/client/src/utils/query-provider.tsx +++ b/apps/client/src/utils/query-provider.tsx @@ -1,14 +1,51 @@ "use client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +// Since QueryClientProvider relies on useContext under the hood, we have to put 'use client' on top +import { + isServer, + QueryClient, + QueryClientProvider, +} from "@tanstack/react-query"; -const queryClient = new QueryClient(); +function makeQueryClient() { + return new QueryClient({ + defaultOptions: { + queries: { + // With SSR, we usually want to set some default staleTime + // above 0 to avoid refetching immediately on the client + staleTime: 60 * 1000, + }, + }, + }); +} + +let browserQueryClient: QueryClient | undefined = undefined; + +function getQueryClient() { + if (isServer) { + // Server: always make a new query client + return makeQueryClient(); + } else { + // Browser: make a new query client if we don't already have one + // This is very important, so we don't re-make a new client if React + // suspends during the initial render. This may not be needed if we + // have a suspense boundary BELOW the creation of the query client + if (!browserQueryClient) browserQueryClient = makeQueryClient(); + return browserQueryClient; + } +} export default function QueryProvider({ children, }: { children: React.ReactNode; }) { + // NOTE: Avoid useState when initializing the query client if you don't + // have a suspense boundary between this and the code that may + // suspend because React will throw away the client on the initial + // render if it suspends and there is no boundary + const queryClient = getQueryClient(); + return ( {children} );