返回 presentation-ai
TanstackProvider.tsx
根目录 / src / provider / TanstackProvider.tsx
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
5 import {
6 isServer,
7 QueryClient,
8 QueryClientProvider,
9 } from "@tanstack/react-query";
10
11 function makeQueryClient() {
12 return new QueryClient();
13 }
14
15 let browserQueryClient: QueryClient | undefined;
16
17 function getQueryClient() {
18 if (isServer) {
19 // Server: always make a new query client
20 return makeQueryClient();
21 } else {
22 // Browser: make a new query client if we don't already have one
23 // This is very important, so we don't re-make a new client if React
24 // suspends during the initial render. This may not be needed if we
25 // have a suspense boundary BELOW the creation of the query client
26 if (!browserQueryClient) browserQueryClient = makeQueryClient();
27 return browserQueryClient;
28 }
29 }
30
31 export default function TanstackProvider({
32 children,
33 }: {
34 children: React.ReactNode;
35 }) {
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 }
46
46 lines Plain Text