Blog>
Snippets

Setting Up React Query for SSR

Demonstrate how to configure React Query for server-side rendering, including the setup of QueryClient and its provider.
import { QueryClient, QueryClientProvider, Hydrate } from 'react-query';
First, import QueryClient, QueryClientProvider, and Hydrate from react-query. Hydrate is essential for server-side rendering as it allows the state from the server to be passed down and used client-side.
const queryClient = new QueryClient();
Create a new instance of QueryClient. This object is used by React Query for caching and managing server state.
function MyComponent({ dehydratedState }) {
  return (
    <QueryClientProvider client={queryClient}>
      <Hydrate state={dehydratedState}>
        {/* Your Application Components Here */}
      </Hydrate>
    </QueryClientProvider>
  );
}
Wrap your application's component inside Hydrate and QueryClientProvider. Pass the dehydrated state received from getServerSideProps (or getStaticProps) to Hydrate to be rehydrated.
export async function getServerSideProps(context) {
  const queryClient = new QueryClient();
  await queryClient.prefetchQuery('todos', fetchTodos);
  return {
    props: {
      dehydratedState: dehydrate(queryClient),
    },
  };
}
In getServerSideProps (or getStaticProps), instantiate a new QueryClient, use it to prefetch any needed data with prefetchQuery, and return the dehydrated state of the QueryClient as a prop using dehydrate. This state will then be passed to Hydrate on the client-side.