Persist using redux-persist

In my recent project the requirement was to persist the data on refreshing the page, the first approach I thought was to store each data in localStorage but that would be a very huge task as the data is too big. So, in our project, we were using the redux, so thought is to, why not make use of it, Redux provides the library called redux-persist which allows saving the redux store in the local storage of the browser.

This article illustrates, with a basic example, how persistence works with your Redux store. In our example first, we create an input box that stores the name in the redux store and that name is used to show on the browser.

The problem is that the output name is not visible once we refresh the page, what we'll do is use the redux-persist to persist out output name.

Redux Persist takes your Redux state object and saves it to local storage or session storage depend upon what we get from the package. Then on every page refresh, it retrieves this persisted state and saves it back to redux. So we will go step by step from installation to actually persist the data.

Step1 : Install redux-persist

It has been provided with the npm package manager: npm install redux-persist

Step2 : Setup persistReducer and persistStore

persistStore: It allows the browser to store the state depending upon the certain configuration. The store which we created using createStore, we pass in the persistStore.

storage: It is basically local storage that we have imported from redux-persist lib.Though we can have also the session storage depending upon the requirement.

We will create a configuration which is just a JSON, where we need to define the key which tells at what point of reducer we want to store everything and we start from the root. Second, we pass the storage and finally, we can pass whitelist or backlist also, which is nothing just tells what reducers should include or not, for now, we are not using this two.

persistReducer: Now we are going to store the root reducer to the persist reducer, we need to pass our config file in it also. It will return the modified reducer with persistence capabilities.

Step3: Setup PersistGate

In the final step, we have to wrap our root component with PersistGate. It will take the persistor so that our application has the access to the persistence store of itself. It will rehydrate our application whenever our page refreshes.

So, here will we see the output result:

❤️ Like, Share or Leave A Comment!

If you enjoyed this post, don’t forget to give it a 👏🏼, share it with a friend you think might benefit from it, and leave a comment!. Any feedback is greatly appreciated.

Thanks !!

--

--