preface

πŸ“¦ repository links to the React-Todo Gitee repository

πŸ’» Online preview Effect React-Todo development progress

Create React App+Tailwind CSS +Material UI

# πŸ‘€ learn React from the ground up next day ~React configure Eslint+ router-dom

# πŸ‘€ Learn React from scratch 3 days ~React date selector component development +Dayjs use

# πŸ‘€ Start from scratch learn React day 4 ~πŸ“† implement a nice popover calendar component

# πŸ‘€ learn React from scratch day 5 ~πŸ“ˆ implement hook related performance optimization

# Never fear too many components! πŸ“¦Redux+Redux Toolkit Introduces concepts and uses

Introduction to state persistence

First of all, we need to understand what state persistence means. In simple terms, it means to store the data in the web page, so that we can avoid the loss of data when we close the page or press refresh. Generally speaking, most of our data are stored in the server database and obtained through network requests, so the front end does not need to worry about data loss.

However, some simple data storage in the client side will be more convenient, such as the current selected items of the navigation of the website page, the show and hide of the popup window, the position of the page scroll. These can be stored directly in the client. Persistence not only reduces the sense of fragmentation caused by style changes when the user refreshes the page, but also improves performance by reducing the number of requests and the amount of data transferred at a time.

We usually use localStorage and sessionStroage apis for client-side storage in browsers, but their use is not detailed here. When using front-end frameworks, we often use related state management tools, such as Vuex or Redux, to help us quickly manage global state, reduce the flow of large amounts of business irrelevant data between components, and provide responsive operations on global data.

But these state management tools typically store data in temporary memory that we reinitialize as soon as the page is refreshed. Therefore, we can make a persistent operation of the repository created by the state management tool, so that all components can quickly share data, but also ensure that the data is not destroyed when the site shuts down.

React uses the redux-Toolkit library # redux-Presist to implement persistent state management in react. There is no fear of too many components! πŸ“¦Redux+Redux Toolkit Introduces concepts and uses

Implement persistence

The installation

Install the story – presist

yarn add redux-persist
Copy the code

configuration

In the Redux-Presist documentation, we are provided with an example code for introduction:

import { createStore } from 'redux'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web

import rootReducer from './reducers'

const persistConfig = {
  key: 'root',
  storage,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

export default() = > {let store = createStore(persistedReducer)
  let persistor = persistStore(store)
  return { store, persistor }
}
Copy the code

However, the above sample code uses redux’s createStore API to create the repository, whereas the previous initialization used The configureStore provided by Redux-Toolkit. If you look directly at the case provided by the government, you may be at a loss how to change it.

Let me drop the code from the redux entry file before I introduced redux-Presist:

// store/index.js
import { configureStore } from "@reduxjs/toolkit"
import date from "./modules/date"
import todo from "./modules/todo"
import drawer from "./modules/drawer"

export default configureStore({
    reducer: {
        date,
        todo,
        drawer,
        // Put the modules here

    },
    middleware: (getDefaultMiddleware) = >
        getDefaultMiddleware({
            serializableCheck: false,})})Copy the code

Based on the above code and the redux-Presist example code, there are two missing variables: rootReducer and store. Where do these two variables come from?

Generate rootReducer

The first is rootReducer. There was a reducer object in the parameters we passed in configureStore. I passed the modules fragments I defined, so I was wondering if it was this object. Actually, no, if we want to combine each Slice Reducer Slice into a large Slice, we need to use the combineReducers API.

The combineReducers helper function merges an object consisting of several different Reducer functions as values into a final Reducer function, and then calls the createStore method on this Reducer.

After the merge, the return state key name is controlled by naming different keys for the reducer of the incoming object. For example, you can call combineReducers({todos: myTodosReducer, counter: myCounterReducer}) to change the state structure to {todos, counter}.

So we need to modify the code to merge our modules using combineReducers and pass persistConfig and the merged module as the persistReducer parameters.

import { persistStore, persistReducer } from "redux-persist"
import { combineReducers } from "redux"
import storage from "redux-persist/lib/storage"

const persistConfig = {
  key: 'root',
  storage,
}
const persistedReducer = persistReducer(
  persistConfig,
  combineReducers({
    date,
    todo,
    drawer,
    // Put the modules here}))Copy the code

Redux-presist storage engine

PersistConfig is an API that supports storage. The persistConfig API uses localStorage and sessionStroage for client-side storage in browsers. There are a number of storage engines built into Redux-Persist, because react projects don’t just run in a browser, they can be compiled into applets, apps, etc., so the choice of storage engine depends on what platform you’re developing on. Storage corresponds to localStorage. The following figure shows all storage engines officially provided.

Generate store

The configureStore API is used to create a repository, so its return value is a store. The final entry file is modified as follows:

// store/index.js
import { configureStore } from "@reduxjs/toolkit"
import { persistStore, persistReducer } from "redux-persist"
import { combineReducers } from "redux"
import storage from "redux-persist/lib/storage"
import date from "./modules/date"
import todo from "./modules/todo"
import drawer from "./modules/drawer"

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

const persistedReducer = persistReducer(
  persistConfig,
  combineReducers({
    date,
    todo,
    drawer,
    // Put the modules here}))export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) = >
    getDefaultMiddleware({
      serializableCheck: false,})})export const persistor = persistStore(store)
Copy the code

Next, let’s modify index.js. Here, we can operate according to the official example. The code I implemented is as follows:

import React from "react"
import ReactDOM from "react-dom"
import "./index.css"
import App from "./App"
import reportWebVitals from "./reportWebVitals"
import { BrowserRouter } from "react-router-dom"
import { store, persistor } from "./store/index"
import { PersistGate } from "redux-persist/integration/react"
import { Provider } from "react-redux"
ReactDOM.render(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <BrowserRouter>
        <React.StrictMode>
          <App />
        </React.StrictMode>
      </BrowserRouter>
    </PersistGate>
  </Provider>.document.getElementById("root"))Copy the code

inspection

After the configuration is complete, we can open the developer tool of the browser, select Local Storage from the top Application menu, we can see the data persist:root, which stores our global state. Of course, you can configure only part of the module, according to the official documentation of the specific operation can be.

conclusion

This article first introduces the meaning and function of state persistence, and then implements the redux-Tookit create repository persistence transformation, finally successfully see our stored data in localStorage.

If you think the article is good or helpful to you, you can point a praise ~ Vuex article is also on the way, welcome to pay attention to insert an eye, please look forward to!