Blog>
Snippets

Setting Up React Query with Server-Side Rendering

Demonstrate how to set up React Query in a React application that uses server-side rendering. Show the initialization of the QueryClient and wrapping the application component with QueryClientProvider and Hydrate components.
import { dehydrate, Hydrate, QueryClient, QueryClientProvider } from 'react-query';
Import the necessary modules from react-query.
function MyApp({ Component, pageProps }) {
  const queryClient = new QueryClient();
  return (
    <QueryClientProvider client={queryClient}>
      <Hydrate state={pageProps.dehydratedState}>
        <Component {...pageProps} />
      </Hydrate>
    </QueryClientProvider>
  );
}
Wrap the application component with QueryClientProvider and Hydrate to enable React Query in a Next.js app. The Hydrate component is used for server-side rendering.
export async function getServerSideProps() {
  const queryClient = new QueryClient();
  await queryClient.prefetchQuery('todos', fetchTodos);
  return {
    props: {
      dehydratedState: dehydrate(queryClient),
    },
  };
}
Use getServerSideProps for server-side data fetching and dehydrating. Here, 'fetchTodos' represents a function that fetches data, which could be replaced with any data fetching function according to your needs.