Blog>
Snippets

Hydrating the Redux Store on the Client

Show how to hydrate an initial state from server rendering within the Redux store on the client side, using Next.js's getInitialProps or getServerSideProps.
import { initializeStore } from '../store';

// This could be inside _app.js or a specific page component
const MyComponent = ({ initialReduxState }) => {
  const store = initializeStore(initialReduxState);
  // ... use store with Provider, etc.
};

// Corresponding getInitialProps or getServerSideProps
MyComponent.getInitialProps = async (ctx) => {
  const reduxStore = initializeStore();
  const { dispatch } = reduxStore;

  // Dispatch actions if needed
  // dispatch(someAction());

  // Return the initial state:
  // This state will be used to hydrate the store on the client side
  return { initialReduxState: reduxStore.getState() };
};

export default MyComponent;
This chunk of code is responsible for hydrating the Redux store on the client side. First, it initializes the store in getInitialProps or getServerSideProps with some optional dispatches, then it passes the initial state from server-side Redux store to the client-side component through the 'initialReduxState' prop. The component initializes the client-side store with this state to ensure the store is hydrated properly.