DEV Community

Sasith Warnaka
Sasith Warnaka

Posted on • Updated on

Redux with Persistent State Rehydration in Next.js

In a Next.js application, incorporating Redux for state management and persisting and rehydrating the state is crucial for ensuring a seamless user experience. This tutorial will guide you through setting up Redux and using Redux Persist for state persistence and rehydration in a Next.js application.

Prerequisites

Before getting started, make sure you have Node.js and npm installed on your machine. If not, you can download and install them from the official website.

Step 1: Creating a Next.js Application

Let's begin by creating a new Next.js application. Open your terminal and execute the following command:

npx create-next-app my-next-app
Enter fullscreen mode Exit fullscreen mode

Replace my-next-app with the desired name for your project. This command sets up a new Next.js application for you.

Step 2: Installing Redux and Redux Persist

To add Redux and Redux Persist to your project, run the following command in your project's root directory:

npm install redux react-redux redux-persist
Enter fullscreen mode Exit fullscreen mode

This will install the necessary dependencies for Redux and Redux Persist.

Step 3: Setting Up Redux

In your Next.js project, create a folder named redux inside the src directory. This folder will house your Redux configuration.

Inside the redux folder, create a file named store.js to set up your Redux store and include Redux Persist:

// src/redux/store.js

import { createStore } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import rootReducer from './reducers';

const persistConfig = {
  key: 'root',
  storage,
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = createStore(persistedReducer);
export const persistor = persistStore(store);
Enter fullscreen mode Exit fullscreen mode

Step 4: Create Reducers

Inside the redux folder, create a folder named reducers. This is where you'll define your reducers. For this example, let's create a simple counter reducer. Inside the reducers folder, create a file called counterReducer.js:

// src/redux/reducers/counterReducer.js

const initialState = {
  count: 0,
};

const counterReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
};

export default counterReducer;
Enter fullscreen mode Exit fullscreen mode

Step 5: Creating Actions

In your redux folder, create a folder named actions. Create a file named counterActions.js to define your actions:

// src/redux/actions/counterActions.js

export const increment = () => ({
  type: 'INCREMENT',
});

export const decrement = () => ({
  type: 'DECREMENT',
});
Enter fullscreen mode Exit fullscreen mode

Step 6: Integrating Redux into Next.js

In your Next.js application, you need to integrate Redux. Create a file named _app.js in the pages directory. This file is special in Next.js and wraps your entire application with global components. Import the Provider component from react-redux, your Redux store, and the PersistGate component from redux-persist/integration/react:

// pages/_app.js

import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { store, persistor } from '../src/redux/store';

function MyApp({ Component, pageProps }) {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <Component {...pageProps} />
      </PersistGate>
    </Provider>
  );
}

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

Step 7: Using Redux in a Component

You can now use Redux in your components. Let's create a simple counter component to demonstrate how Redux works. In the pages directory, create a file named index.js:

// pages/index.js

import { useDispatch, useSelector } from 'react-redux';
import { increment, decrement } from '../src/redux/actions/counterActions';

export default function Home() {
  const count = useSelector((state) => state.count);
  const dispatch = useDispatch();

  return (
    <div>
      <h1>Redux Counter Example</h1>
      <p>Count: {count}</p>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

You have successfully set up Redux with state persistence and rehydration in your Next.js application. With Redux Persist, your application's state will be saved and restored even after page refreshes or navigation.

Feel free to expand upon this basic example and implement more advanced features as your project requires. Redux and Redux Persist offer a robust solution for state management in Next.js applications. Happy coding!

Top comments (1)

Collapse
 
flyingwolf1701 profile image
Patrick Reid

Thank you for this. It would be nice if you used app router instead of pages router since no one is building new things with pages. or maybe showed both. Thanks for writing this.