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.
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 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?
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.
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);
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.
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
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.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork