Blog>
Snippets

State Hydration in Next.js with TanStack Store

Provide an example of how to hydrate the client-side state with server-side data in a Next.js application using TanStack Store, emphasizing the process of fetching initial state in `getServerSideProps` and hydrating the store on the client side.
import { getServerSideProps } from 'next';
import { dehydrate, QueryClient } from '@tanstack/react-query';

export const getServerSideProps = async () => {
  const queryClient = new QueryClient();

  await queryClient.prefetchQuery(['key'], async () => {
    // Fetch data from your API
    return fetchData();
  });

  return {
    props: {
      dehydratedState: dehydrate(queryClient),
    },
  };
};
This code snippet demonstrates how to fetch initial state server-side using `getServerSideProps` in Next.js. It utilizes `@tanstack/react-query` for data fetching and caching. The fetched data is then dehydrated so it can be passed down as props.
import { Hydrate, QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useState } from 'react';

export default function MyApp({ Component, pageProps }) {
  const [queryClient] = useState(() => new QueryClient());

  return (
    <QueryClientProvider client={queryClient}>
      <Hydrate state={pageProps.dehydratedState}>
        <Component {...pageProps} />
      </Hydrate>
    </QueryClientProvider>
  );
}
This code snippet goes into `_app.js` of a Next.js application. It wraps the application with `QueryClientProvider` from `@tanstack/react-query` and uses `Hydrate` to rehydrate the client-side state with the server-side data fetched in `getServerSideProps`, making the initial server-state available in the client-side.