How to Set Up and Use Redux Persist in Redux Store

This post will help us understand the concept of adding Redux Persist to the Redux Store in React js. Also, how to use Redux persist to store Redux state in the browser’s localStorage.

When we refresh the web page all the data on the web page goes away, in some cases we need to retain the data on the web page. Such as shopping carts, user data, and access tokens are perfect examples of such scenarios.

The redux-persist library helps us in storing the redux state. We can persist redux state not just in local storage, but also in session storage, and async storage.

Hence, we will cover how to make a request to the server using the RTK query, receive a response from the server, and save the API response into the local storage.

How to Configure Redux Persist in Redux Store

  • Step 1: Create React Application
  • Step 2: Install Redux Libraries
  • Step 3: Build Query with fetchBaseQuery
  • Step 4: Integrate Persist to Redux
  • Step 5: Display Persisted State
  • Step 6: Add Component to App.js
  • Step 7: Start React Server

Create React Application

The first step begins by creating a new React app; we can do it by running the CRA command.

npx create-react-app react-redux-persist-example

Install Redux Libraries

Redux persist doesn’t come with redux, this library is added in React using the npm registry.

To build the functionality; we have to install some packages. Here is the command that you need to execute.

npm install react-redux @reduxjs/toolkit bootstrap

Build Query with fetchBaseQuery

You have to make the features/ directory in src/ folder, make the apiSlice.js file and write the query using createApi, and fetchBaseQuery modules.

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const apiSlice = createApi({
  reducerPath: 'apiSlice',
  baseQuery: fetchBaseQuery({
    baseUrl: 'https://jsonplaceholder.typicode.com',
  }),
  tagTypes: ['Users'],
  endpoints: (builder) => ({
    getUsers: builder.query({
      query: () => '/users',
      providesTags: ['Users'],
    }),
  }),
})

export const { useGetUsersQuery } = apiSlice

Integrate Persist to Redux

Use the command to install the redux-persist library in React application using the npm registry.

npm install redux-persist

Next, you have to build the app/ directory with the store.js file, in this file we will create the redux store and bind the redux store to redux persist using the given code.

import { configureStore } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/query";

import { combineReducers } from "@reduxjs/toolkit";
import { apiSlice } from "../features/apiSlice";

import storage from "redux-persist/lib/storage";

import {
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from "redux-persist";

const persistConfig = {
  key: "root",
  storage: storage,
};

export const rootReducers = combineReducers({
  [apiSlice.reducerPath]: apiSlice.reducer,
});

const persistedReducer = persistReducer(persistConfig, rootReducers);

const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }).concat(apiSlice.middleware),
});

setupListeners(store.dispatch);

export default store;

Now, you have to inject the redux persist with the redux store, for that you need to add the given code to the index.js file.

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

import { persistStore } from "redux-persist";
import { PersistGate } from "redux-persist/integration/react";
import { Provider } from "react-redux";

import store from "./app/store";
let persistor = persistStore(store);

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
  <Provider store={store}>
    <PersistGate persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>
);

Display Persisted State

Head over to components/ folder, make the users/Users.js folder and file, use the following code to use the useGetUsersQuery hook for handling API response in react component.

import React, { useEffect } from "react";
import { useGetUsersQuery } from "../../features/apiSlice";
import { useDispatch } from "react-redux";

function Users() {
  const dispatch = useDispatch();

  const { data, isLoading, isSuccess, isError, error } = useGetUsersQuery();

  useEffect(() => {}, [dispatch]);

  let content;

  if (isLoading) {
    content = (
      <div className="d-flex justify-content-center w-100">
        <div className="spinner-border text-primary">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  } else if (isSuccess) {
    content = data.map((item) => {
      return (
        <div className="col" key={item.id}>
          <div className="card h-100">
            <div className="card-body">
              <h5 className="card-title">${item.name}</h5>
              <p className="card-text">{item.email}</p>
            </div>
          </div>
        </div>
      );
    });
  } else if (isError) {
    content = (
      <div className="alert alert-danger w-100">
        {error.status} {JSON.stringify(error)}
      </div>
    );
  }

  return <div>{content}</div>;
}

export default Users;

Add Component to App.js

You now need to inject the Users component in the App.js file. Here is the code that you can use to register the component in react global component.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import Users from "./components/users/Users";

function App() {
  return (
    <div className="container mt-5">
      <Users />
    </div>
  );
}

export default App;

Start React Server

Let us run the react app, and save the redux state in localStorage.

npm start
http://localhost:3000

Open the app on the given URL, then open the browser’s console, and head over to the Application tab there you can see the persisted state.

How to Set Up and Use Redux Persist in Redux Store

Summary

Redux persist is a great library. It offers great features. One of the best feature we liked about redux persist is the Blacklist & Whitelist.

It gives you complete freedom to include or not to include the redux reducer in redux persist in conjunction with storing the state in localstorage.

In this tutorial, we have learned how to add redux persist in React js application and how to use redux persist with redux architecture to store redux state in browser’s localstorage.