Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

root-provider.tsx

37 lines884 Bytes

1import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
2​
3// Client-side singleton to ensure the same instance is used across the app
4let clientQueryClient: QueryClient | null = null;
5​
6function makeQueryClient() {
7 return new QueryClient();
8}
9​
10export function getContext() {
11 // Server: always create a new QueryClient per request to avoid data leaks
12 if (typeof window === "undefined") {
13 return {
14 queryClient: makeQueryClient(),
15 };
16 }
17​
18 // Client: use singleton to preserve cache across navigations
19 if (!clientQueryClient) {
20 clientQueryClient = makeQueryClient();
21 }
22 return {
23 queryClient: clientQueryClient,
24 };
26​
27export function Provider({
28 children,
29 queryClient,
30}: {
31 children: React.ReactNode;
32 queryClient: QueryClient;
33}) {
34 return (
35 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
36 );