Redux Persist: The Key to Preserving Your Redux State

In this blog, we will cover the redux persist react library. With the help of the redux persist library, developers can save the redux state. Even after refreshing the site, the browser state gets still preserved.

Every local state in the component is persisted for all reducers, and the persisted store replaces state content. Reducer replaces their content with the persisted one.

We can persist states by manually using native JavaScript and some methods like localStorage.setItem() and localStorage.getItem(), but honestly, we need to write everything from scratch, and we have to maintain the structure of the state. So that’s why redux-persist brings onto the table, with the help of the redux toolkit, that helps us to rehydrate the state even after refreshing the browser.

Basic Overview Of Some Functionalities

Let’s add persistReducer and persistStore to your setup. 

import { persistReducer, persistStore } from 'redux-persist';

persistReducer returns an enhanced reducer that wraps the rootReducer you pass in and will persist that reducer’s state according to the config you pass in. The reducers themselves are not persisted since they are just functions.

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

The usage of PersistGate automatically provides a delay in rendering the components until the state gets persisted along with the use to show the loading component, as shown below example.

function App() {


 return (
   <div className="App">
     <Provider store={store}>
       <PersistGate loading={null} persistor={persistor}>
         <Dashboard />
       </PersistGate>
     </Provider>
   </div>
 );

}

How many levels of state do they want to “merge”? Every app needs to decide. The default is 1 level. We need the combineReducers function to pass it to the redux persist for a group of all reducers into one.

Let’s look into how we set it up with a redux toolkit for state or store persisting. We will use simple word adding in the state for easier understanding. Which is task creator 

Local Storage And Session Storage

Local storage and Session storage are web storage objects, allowing the saving of the key/value pairs in the browser storage.

We already have cookies for saving the data. So why do we need additional storage objects there?

  • Session storage has only the current session browser tab, and the Local storage shares among all windows and tabs in the browser.
  • Unlike cookies, with each request, web storage objects are not sent to the server. We can store much more because of that. Most modern browsers allow at least 5 megabytes of data storage capacity (or more) and have configurable settings.
  • Via HTTP headers, the server can manipulate storage objects. Everything’s configured in JavaScript.
  • The storage is bound to the origin (protocol/port triplet/domain). Different protocols/Subdomains infer different storage objects; they can’t access data from each other.
  • Local and Session both storage objects provide the same methods and properties.

Methods

setItem(key, value) – store key/value pair.
getItem(key) – get the value by key.
removeItem(key) – removes the key with its value.
clear() – delete everything.
key(index) – return the key on a given position.
length – the number of stored items.
As you can see, it’s just like a Map collection (removeItem/setItem/getItem). The index can access it with a key (index).

Let’s see how it works.

Implementation With Task Creator Example

Step 1

Installing redux-persist and redux-toolkit in the project.

npm install redux-persist

npm install @reduxjs/toolkit

Step 2

Need to Import the necessary module for the project.

//store.js
import storage from 'redux-persist/lib/storage';
import { combineReducers } from 'redux';
import {
    persistReducer,
    FLUSH,
    REHYDRATE,
    PAUSE,
    PERSIST,
    PURGE,
    REGISTER,
} from 'redux-persist';

Redux persist provides storage like local storage, session storage or async storage to persist data. In this example, we will use local storage.
To combine all reducers in one, we will use { combineReducers } from redux to pass it to the redux-persist for persistent storage.
The redux persist library dispatches some functions, and according to the official redux-toolkit guide, we need to add those to the ignore list to avoid unnecessary warnings and errors.

Step 3

As shown in the below code, we need to add configured persist object that will be stored in the storage. 

//store.js
const persistConfig = {
    key: 'counter',
    storage,
};

We need to determine which storage we will use, and the key specifies the ID of the persistent object.

Step 4

Combine the reducers:

const reducers = combineReducers({
   "root": rootReducer
})

Step 5

Create a persistent reducer:

//store.js
const persistedReducer = persistReducer(persistConfig, reducers);

Hire Our Expert React JS Developers

Step 6

Let’s configure the store using configureStore provided by redux-toolkit. We are not going to use createStore from redux because it will be deprecated soon, so let us assign the persistingReducer to the reducer and also add ignore list into middleware in the ignoreActions to avoid unnecessary errors and warnings as shown in the below code snippet :

export const store =  configureStore({
   reducer: persistingReducer,
   middleware: (getDefaultMiddleware) =>
       getDefaultMiddleware({
           serializableCheck: {
               // need to add unnecessary action in a list for avoiding
               // errors and warning
               ignoredActions: [
                        PERSIST,
                        FLUSH, 
                        REHYDRATE, 
                        PAUSE, 
                        PURGE,
                        REGISTER
                        ],
           },
       }),
});
export const persistor = persistStore(store)

Step 7

React-redux provides us, Provider, for providing a store; likewise, redux-persist provides PersistGate, which we can wrap the whole component within. Your code looks like the below code.

import React from 'react';
import { Provider } from 'react-redux';
import Navbar from '../Components/Navbar';
import Dashboard from '../Page/Dashboard';
import './App.css';
import { store, persistor } from '../Utils/store';
import { PersistGate } from 'redux-persist/integration/react';
import Task from '../Page/Task';


function App() {

 return (
   <div className="App">
     <Provider store={store}>
       <PersistGate loading={null} persistor={persistor}>
         <Navbar />
         <Dashboard />
         <Task/>
       </PersistGate>
     </Provider>
   </div>
 );
}

export default App;

Hence as shown in the above code snippet, before we pass the store object to the persistGate component, we will need to give it from persistStore(store) to become a compatible store object.

Step 8

All set? You will be done with the connection between redux and redux persist. Now your state will be persisted when the page refreshes and change

If we check it in redux-logger, first check with PERSIST action and then { REHYDRATE } actions which rehydrate the store.

Customize What’s Persisted

With the help of blacklist and whitelist, We can customize our state to persist by using these properties of the config object passed to persistReducer.Using the whitelist property, we can persist a specific part that will appear in the whitelist array, while the blacklist property will not persist specific state. It does exactly the opposite of the whitelist property. Let’s see this in a small example:

const rootReducer = combineReducers({ 
  userData: userDataReducer,
  notesData: notesDataReducer
})

Suppose we won’t persist noteData, so the code is similar to the following.

const rootPersistConfig = {
  key: 'root',
  storage,
  blacklist: ['notesData']
}

// OR

const rootPersistConfig = {
  key: 'root',
  storage,
  whitelist: ['usersData']
}

The Properties of blacklist and whitelist take an array string, as mentioned above in the code. There each string must be matched with a state name. We might be targeted deeply when we use whitelist and blacklist. Hence, we will take advantage of nested persistence if we want to point out a specific object property in our states.

Let’s assume the following example:

const initialState = {
  user: {},
  isLoggedIn: false,
}

Suppose we want to prevent only from persisting, so should do the following steps in code:

const rootPersistConfig = {
  key: 'root',
  storage,
}

const userPersistConfig = {
  key: 'user',
  storage,
  blacklist: ['isLoggedIn']
}

const rootReducer = combineReducers({
  user: persistReducer(userPersistConfig, userReducer),
  notes: notesReducer
})

const persistedReducer = persistReducer(rootPersistConfig, rootReducer);

And now isLoggedIn state won’t be preserved or prevented after refreshing or changing the page. This is a simple example you can change as your project requires. You can refer to this GitHub repo for the reference : Here

coma

Conclusion

To conclude, redux persist is a useful library that allows developers to save the state of a redux store even after the site is refreshed. It makes it easy to set up and customize the way the state is persisted, and can be used in combination with the PersistGate component to show a loading component while the state is being rehydrated. It is a helpful tool for maintaining the state of an app and providing a seamless user experience.

Keep Reading

Keep Reading

Mindbowser is excited to meet healthcare industry leaders and experts from across the globe. Join us from Feb 25th to 28th, 2024, at ViVE 2024 Los Angeles.

Learn More

Let's create something together!