📜  redux-persist - Javascript (1)

📅  最后修改于: 2023-12-03 15:19:47.904000             🧑  作者: Mango

Redux Persist

Redux Persist is a library that allows for easy and persistent storage of Redux state, even when the browser or device is closed. It is a simple and lightweight library that is easy to add to your Redux project.

Installation

To install Redux Persist, simply run the following command:

npm install redux-persist
Usage

To use Redux Persist in your Redux project, you need to first import it and initialize it in your Redux store:

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

const rootReducer = combineReducers({
  // your reducers here
});

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

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = createStore(persistedReducer);
export const persistor = persistStore(store);

This will add Redux Persist to your Redux store, with the default configuration of using local storage for web and async storage for React Native.

Configuration Options

You can configure Redux Persist using the persistConfig object. The available options are:

  • key: The key to use for storing the persisted data. This should be unique to your application.
  • storage: The storage engine to use. This can be any compatible storage engine such as local storage or async storage.
  • whitelist: An array of reducer keys to persist. Any reducer not listed here will not be persisted.
  • blacklist: An array of reducer keys to exclude from persisting.
Conclusion

Redux Persist is a great library for adding persistent storage to your Redux applications. It's easy to use and configure, and can make a big difference for users who need to leave and come back to your application.