Preloading Server-State with MutationCache for SSR
Showcase a technique for utilizing MutationCache to preload server state in an application using Server-Side Rendering (SSR), ensuring smooth state hydration.
import { QueryClient, MutationCache } from 'react-query';
// Initialize a new QueryClient with a MutationCache
const queryClient = new QueryClient({
mutationCache: new MutationCache({
// Optionally, specify a mutation cache configuration
onError: (error, variables, context) => {
// Handle global mutation errors
},
onSuccess: (data, variables, context) => {
// Handle global mutation successes
}
})
});
This piece of code initializes React Query's QueryClient with a customized MutationCache. The MutationCache is configured with global onSuccess and onError handlers for all mutations.
import { dehydrate, hydrate } from 'react-query/hydration';
// Function to pre-fetch and pre-load state on the server-side
async function prefetchServerState(fetchFunction) {
await queryClient.prefetchMutation('uniqueKey', fetchFunction);
return dehydrate(queryClient);
}
// On the server, call this function with the mutation fetchFunction
// Represents a server-side function to fetch initial state
const serverState = await prefetchServerState(serverFetchFunction);
This code demonstrates how to prefetch mutation state on the server and dehydrate it. `fetchFunction` would be an async function that triggers a mutation. The dehydrated state can then be passed to the client.
import { QueryClientProvider } from 'react-query';
import { Hydrate } from 'react-query/hydration';
// On the client-side
// Rehydrate the state on the client
function MyApp({ Component, pageProps }) {
const { dehydratedState } = pageProps;
const queryClient = new QueryClient();
hydrate(queryClient, dehydratedState);
return (
<QueryClientProvider client={queryClient}>
<Hydrate state={dehydratedState}>
<Component {...pageProps} />
</Hydrate>
</QueryClientProvider>
);
}
On the client-side, this snippet shows how to wrap your application's component tree with `QueryClientProvider` and `Hydrate` from React Query, using the dehydrated state received from the server to ensure state is correctly rehydrated. `MyApp` is your Next.js App component or a similar top-level component in other frameworks.