Guide to set up Redux in React with Persistence

What is Redux?

Redux follows the one-way data flow of React. Redux keeps the state of the application in a single read-only JS object. To change the state we dispatch actions and reducers process the changes. All the reducers receive all the actions.

What is Persistence?

Persistence is “the continuance of an effect after its cause is removed”. In the context of storing data in a computer system, this means that the data survives after the process with which it was created has ended. In other words, for a data store to be considered persistent, it must write to non-volatile storage.

A Simple example representing React-Redux with Persistence.

In this example, I will be persisting the data of the user when login in and logout.

The entire code for this can be found here:

To start off I have created a simple form that takes in username and password when logs in.

Simple username login form

Once the user logs in I need to store the user's data into a state which can be used everywhere within the project and also persist the data (meaning in simple terms that when you hard refresh the browser no data should be lost)

Project Structure

Firstly let's set up the store:

Creating the store

I have also created a file for persisting the data:

Now let’s create something called a slice in this case a “userSlice”, this file will contain the reducer necessary to work with login and logout functionality.

userSlice

I am using Google Chrome for development and make sure you have the Redux dev tools extension installed, this helps you to visualize your states clearly and get a good understanding of what's happening even if something goes wrong.

before login

The above image shows the state on the right-hand side using Redux dev tools that the user is set to null initially when the user didn't log in, which makes sense because there won’t be any data of the user unless he logs in.

after login

Once the user logs in you can see on the right-hand side that the details of the logged-in user are stored in a variable called user and even if you hard refresh the page the data of the user won’t be lost and only when u log out the user data will be removed.

Great, so there we have Redux with persistence applied to a simple user object data, you can use this concept for any other requirements as well.

Happy Coding!