SoFunction
Updated on 2025-04-07

Recording process of using redux-persist in react for persistent storage

Use redux-persist for persistent storage in react

One afternoon, having fun – Notes

Installation-related dependencies

npm install @reduxjs/toolkit redux-persist redux react-redux
// 
import { configureStore, getDefaultMiddleware } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage"; // Choose a persistent storage engine such as localStorage or AsyncStorageimport rootReducer from "./reducers/index"; // Import your root reducer// Configure persistence settingsconst persistConfig = {
  key: "root", // Stored key name  storage, // Persistent storage engine  // Optional configuration items, such as whitelist, blacklist, etc. Just choose one of them  // blacklist:['test'], // Only test will not be cached  // whitelist: ["test"], // Only test will be cached};
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = configureStore({
  reducer: persistedReducer,
  middleware: getDefaultMiddleware({
    serializableCheck: false, // Disable strict mode  }),
});
const persistor = persistStore(store);
export { store, persistor };

Provide the store to the application: Provide the Redux store to the root component so that the Redux state can be accessed throughout the application

// 
import React from "react";
import ReactDOM from "react-dom/client";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import { store, persistor } from "./redux/store";
import App from "./App";
(("root")).render(
  <>
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <App />
      </PersistGate>
    </Provider>
  </>
);

Example of reducer:

// reducers/
import { combineReducers } from "redux";
import userReducer from "./user";
import baseReducer from "./base";
const rootReducer = combineReducers({
  user: userReducer,
  base: baseReducer,
});
export default rootReducer;
// reducers/
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
  token: "Default value token",
  isLogin: false,
};
const user = createSlice({
  name: "user",
  initialState,
  reducers: {
    setToken: (state, action) =&gt; {
      // Set the passed value to the new value of token       = ;
    },
  },
});
export const { setToken } = ;
export default ;

Use in components

// 
import { useSelector, useDispatch } from "react-redux";
import { setToken } from "./redux/reducers/user";
const App = () =&gt; {
  const user = useSelector((state) =&gt; );
  // Use useDispatch in the page component to get the dispatch function, which is used to distribute action  const dispatch = useDispatch();
  const setTokenFun = () =&gt; {
    dispatch(setToken("A new token"));
  };
  return (
    &lt;&gt;
      &lt;p&gt;token=====:{}&lt;/p&gt;
      &lt;Button type="primary" onClick={setAddressFun}&gt;
        Set Token
      &lt;/Button&gt;
    &lt;/&gt;
  );
};
export default App;

Supplement: Use of React-persist (data persistence)

In React projects, we often store and manage global data through redux and react-redux. However, when storing global data through redux, there will be a problem. If the user refreshes the web page, then all the global data we store through redux will be cleared, such as login information.

At this time, we will have the need for global data persistent storage. The first thing we think of is localStorage. localStorage is a data storage without time limits. We can use it to realize persistent data storage.

However, on the basis of using redux to manage and store global data, we then use localStorage to read and write data. This not only has a huge workload, but also has a high risk of errors. So is there a framework that combines redux to achieve persistent data storage functions? Of course, it's redux-persist. redux-persist will cache the data in the redux store to the browser's localStorage.

1. Installation

$ npm install redux-persist --save

2. Use

/*
	 This file is specifically used to expose a store object, and the entire application has only one store object
 */
//Introduce createStore, specifically used to create the most core store object in reduximport { createStore, applyMiddleware ,combineReducers} from 'redux'
//Introduce redux-persist persistenceimport { persistStore, persistReducer } from 'redux-persist'
// import localStorage from 'redux-persist/lib/storage'
import storage from 'redux-persist/lib/storage/index'
//Introduce reducer serving Count componentimport incrementReducer from './incrementReducer';
import personReducer from './personReducer';
//Introduce middleware and pass in action as a functionimport thunk from 'redux-thunk';
// Introduce redux-devtools-extension, a third-party visualization tool for reduximport {composeWithDevTools} from 'redux-devtools-extension'
// import {composeWithDevTools} from 'redux-devtools-extension'
//Implement persistent dataconst config = {
  key: 'root',
  storage:storage, //The storage introduced has local or session}
//There are redux complete key and value stored inside the mapStateToProps to mobilize the keyconst allReducer = combineReducers({
  incrementReducer,
  personReducer
})
const store = createStore(persistReducer(config,allReducer),composeWithDevTools(applyMiddleware(thunk)))
persistStore(store)
export default store
//The normal version exposes the store, thunk ensures that the action can receive functions// export default createStore(reducer, applyMiddleware(thunk))

The process of reducer and action remains unchanged, just modify the store's generated code

This is the end of this article about using redux-persist for persistent storage in react. For more related react redux-persis persistent storage content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!