乐闻世界logo
搜索文章和话题

How to configure redux-persist with redux-toolkit ?

1个答案

1

When configuring Redux persistence with Redux Toolkit, we typically combine it with the Redux Persist library. Redux Persist enables storing Redux state in browser storage (such as localStorage or sessionStorage), allowing the application state to persist after page refreshes. I will now detail how to configure Redux persistence.

Step 1: Install Required Packages

First, we need to install Redux Toolkit and Redux Persist:

bash
npm install @reduxjs/toolkit redux-persist

Step 2: Configure the Persisted Reducer

We need to create a persisted reducer by using the persistReducer function from redux-persist. We also need to specify the storage method and which reducers to persist.

javascript
import { configureStore } from '@reduxjs/toolkit'; import storage from 'redux-persist/lib/storage'; // Default to localStorage import { combineReducers } from 'redux'; import { persistReducer } from 'redux-persist'; import userReducer from './features/userSlice'; import settingsReducer from './features/settingsSlice'; const rootReducer = combineReducers({ user: userReducer, settings: settingsReducer }); const persistConfig = { key: 'root', storage, whitelist: ['user'] // Persist only the user reducer }; const persistedReducer = persistReducer(persistConfig, rootReducer);

Step 3: Create the Redux Store and Integrate the Persisted Reducer

Next, we create the Redux store using Redux Toolkit's configureStore method and include the persisted reducer.

javascript
import { configureStore } from '@reduxjs/toolkit'; import { persistStore } from 'redux-persist'; const store = configureStore({ reducer: persistedReducer }); const persistor = persistStore(store);

Step 4: Use PersistGate in the React Application

To implement Redux persistence in a React application, we wrap the application entry point with the PersistGate component from redux-persist, ensuring that the application restores state from storage when loading.

javascript
import { Provider } from 'react-redux'; import { PersistGate } from 'redux-persist/integration/react'; ReactDOM.render( <Provider store={store}> <PersistGate loading={null} persistor={persistor}> <App /> </PersistGate> </Provider>, document.getElementById('root') );

Summary

By following these steps, we successfully set up Redux persistence to retain specific states after page refreshes. This is highly beneficial in practical development scenarios, such as user authentication states and user preference settings that require persistence.

2024年8月8日 14:45 回复

你的答案