Dehydrating Server State with React Query
Show how to dehydrate the server state using React Query's dehydrate function. Include how to fetch data on the server, use the dehydrate function on the QueryClient, and pass the result to the client.
import { dehydrate, QueryClient } from 'react-query';
export async function getServerSideProps() {
const queryClient = new QueryClient();
await queryClient.prefetchQuery('todos', fetchTodos);
return {
props: {
dehydratedState: dehydrate(queryClient),
},
};
}
This snippet demonstrates fetching data (e.g., a list of to-dos) on the server using React Query's prefetchQuery method. After fetching, it uses the dehydrate function to create a serializable version of the fetched query state, which can then be passed as props to the client for hydration.
import { Hydrate, QueryClient, QueryClientProvider } from 'react-query';
import { useState } from 'react';
function MyApp({ Component, pageProps }) {
const [queryClient] = useState(() => new QueryClient());
return (
<QueryClientProvider client={queryClient}>
<Hydrate state={pageProps.dehydratedState}>
<Component {...pageProps} />
</Hydrate>
</QueryClientProvider>
);
}
In this snippet, we wrap the app's main component with QueryClientProvider and Hydrate components from React Query. We use the dehydrated state passed through pageProps to hydrate the client's query cache, ensuring the client has immediate access to the data fetched on the server without refetching.