Blog>
Snippets

Rehydrating State on the Client with React Query

Illustrate the process of rehydrating the state on the client using React Query. This involves showing how to take the dehydrated state from the server and use the Hydrate component to rehydrate the client state for seamless transition.
import { Hydrate, QueryClient, QueryClientProvider } from 'react-query';
Importing necessary components from react-query for hydration and query management.
const queryClient = new QueryClient();
Initializing a new instance of QueryClient to manage our queries.
function MyApp({ Component, pageProps }) {
  return (
    <QueryClientProvider client={queryClient}>
      <Hydrate state={pageProps.dehydratedState}>
        <Component {...pageProps} />
      </Hydrate>
    </QueryClientProvider>
  );
}
Wrapping the application with QueryClientProvider and Hydrate components. The Hydrate component is given the dehydratedState prop to rehydrate the client state.
// pages/_app.js or pages/_app.tsx
export default MyApp;
Exporting the MyApp component to be used by Next.js as the custom App component.