Blog>
Snippets

Hydrating Server State with React Query

Illustrate the process of hydrating the server state in a React SSR application using React Query's Hydrate component.
import { QueryClient, QueryClientProvider, Hydrate } from 'react-query';
import { useState } from 'react';
Import necessary modules from react-query and React.
function MyApp({ Component, pageProps }) {
  const [queryClient] = useState(() => new QueryClient());
  return (
    <QueryClientProvider client={queryClient}>
        <Hydrate state={pageProps.dehydratedState}>
            <Component {...pageProps} />
        </Hydrate>
    </QueryClientProvider>
  );
}
Setup the QueryClient and wrap the App component with QueryClientProvider and Hydrate to enable hydration.
export async function getServerSideProps(context) {
  const queryClient = new QueryClient();
  await queryClient.prefetchQuery('todos', fetchTodos);
  return {
    props: {
      dehydratedState: JSON.parse(JSON.stringify(dehydrate(queryClient))),
    },
  };
}
Fetch data on the server and dehydrate the state to be passed to the client for hydration.