0

I have been using react query and next.js , I need to know how can achieve server side rendering using react query, I can achieve with this using normal fetch or axios in the server side components, but is there any we can achieve using react query, if use this in any componet that will become a client side component , any solutions on this?

I have tried react query on server side components , but that wont work obiously

1

2 Answers 2

0

https://tanstack.com/query/v4/docs/framework/react/guides/ssr

Haven't tested yet, but The docs says that you can achieve SSR using queryClient.prefetchQuery.

// pages/posts.jsx
import { dehydrate, QueryClient, useQuery } from '@tanstack/react-query'

export async function getStaticProps() {
  const queryClient = new QueryClient()

  await queryClient.prefetchQuery({ queryKey: ['posts'], queryFn: getPosts })

  return {
    props: {
      dehydratedState: dehydrate(queryClient),
    },
  }
}

function Posts() {
  // This useQuery could just as well happen in some deeper child to
  // the "Posts"-page, data will be available immediately either way
  const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })

  // This query was not prefetched on the server and will not start
  // fetching until on the client, both patterns are fine to mix
  const { data: otherData } = useQuery({
    queryKey: ['posts-2'],
    queryFn: getPosts,
  })

  // ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.