Home Blog About Contact

Redux Persist With Next.js

Sun, Sep 26, 21


Redux is a popular state management library to use with React app. It provides a single store to store all of the application data. All components listen to one store to update their layouts instead of passing data up & down the component tree. Redux is convenient to use with client side React app. But when it comes to SSR (Server Side Rendering) React such as Next.js, it requires some more configurations to make them work together.

What is redux persist?

Redux Persist is a library that allows saving a Redux store in the local storage of an application and retrieve the same when open the app for second time.

The following implementation shows you how to integrate Redux Persist into Next.js. First, the installation of the library on the command line:

npm install redux-persist

Second, rather than having a straightforward function which creates our Redux store, we distinguish between server-side and client-side Redux store. In the case of the client-side Redux store creation, we add the implementation to persist our store by default in the local storage between browser sessions:

import { createStore } from 'redux'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web

import rootReducer from './reducers'

const persistConfig = {
  key: 'root',

const persistedReducer = persistReducer(persistConfig, rootReducer)

export default () => {
  let store = createStore(persistedReducer)
  let persistor = persistStore(store)
  return { store, persistor }

Last but not least, in our src/pages/_app.js file which defines our Next.js root component we add additional code for the persistent Redux store:

import { PersistGate } from 'redux-persist/integration/react'

// ... normal setup, create store and persistor, import components etc.

const App = () => {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <RootComponent />

Is it good to use redux persist?


Redux Persist is a powerful library with a simple interface. You can setup automatic persistence of your Redux store in only a few lines of code. Users and developers alike will be thankful for its convenience.

Full Version of Redux Persist With Next.js