How to Use Redux Persist in React JS MERN?

How to Use Redux Persist in React JS MERN

1. Install a Package

npm i redux-persist

2. Add Persist Reducer in “store.js”

store.js:

import { configureStore, combineReducers } from ‘@reduxjs/toolkit’
import userReducer from ‘./user/userSlice’
import {persistReducer, persistStore} from ‘redux-persist’
import storage from ‘redux-persist/lib/storage’

 

const rootReducer=combineReducers({
  user:userReducer
})

 

const persistConfig={
  key:‘root’,
  storage,
  version:1
}
const persistedReducer=persistReducer(persistConfig, rootReducer);

 

export const store = configureStore({
  reducer:persistedReducer,
  middleware:(getDefaultMiddleware)=>getDefaultMiddleware({
    serializableCheck:false
  }),
})

 

export const persistor=persistStore(store);

3. Add persistor in main.jsx –

import React from ‘react’
import ReactDOM from ‘react-dom/client’
import App from ‘./App.jsx’
import ‘./index.css’
import {store, persistor} from ‘./redux/store.js’
import {Provider} from ‘react-redux’
import { PersistGate } from ‘redux-persist/integration/react’
ReactDOM.createRoot(document.getElementById(‘root’)).render(
 <PersistGate persistor={persistor}>
 <Provider store={store}>
    <App />
  </Provider>
  </PersistGate>
)

4. Test it.

 

Video Tutorial: