Yes you can do, but there isn't a stright forward approach, rather what we can do is to prefetch the api on the server and then hydrate the client. By this the data will be cached by react query and during the render on client it uses that cache data. But as you will be getting the data using useQuery hook only, so that page should be client, and the prefetching should be done inside the server component.
here's how I have done this:
1. making the query client and then pass it to provider ->
import { isServer, QueryClient } from '@tanstack/react-query';
const makeQueryClient = () => {
return new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000,
gcTime: 10 * 60 * 1000,
retry: (failureCount, error: unknown) => {
if (typeof error === 'object' && error !== null && 'response' in error) {
const response = (error as { response?: { status?: number } }).response;
if (response?.status && response.status >= 400 && response.status < 500) {
return false;
}
}
return failureCount < 1;
},
},
mutations: {
retry: 1,
},
},
});
};
let browserQueryClient: QueryClient | undefined = undefined;
export const getQueryClient = () => {
if (isServer) {
return makeQueryClient();
} else {
if (!browserQueryClient) browserQueryClient = makeQueryClient();
return browserQueryClient;
}
};
// Server page ->
const ServerComponent = async () => {
const queryClient = new QueryClient();
await queryClient.prefetchQuery({
queryKey: your-query-key,
queryFn: your-query-function
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<ClientComponent/>
</HydrationBoundary>
// Client Component ->
const ClientComponent = () => {
const {data} = useGetData(); // this will be your hook for getting the data -> this will include your fetch function.
}
Now the data here in the client component will be used from cache.
You can read more about it here -> https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr
Also you can go through tkdodo's blog, he's one of the maintainer of react query -> https://tkdodo.eu/blog/practical-react-query