ReasonJun

Redux : toolkit : persistReducer & persistStore 본문

Frontend/Redux

Redux : toolkit : persistReducer & persistStore

ReasonJun 2023. 8. 20. 11:31
728x90

persistReducer and persistStore are two functions provided by the Redux Persist library to persist Redux state to persistent storage.

  • persistReducer takes a configuration object and a reducer as input and returns a new reducer that persists the state to the configured storage. The configuration object specifies the following:
    • The key to use to store the state in the storage.
    • The storage engine to use.
    • The state reconciler to use.
    • The whitelist of state to persist.
    • The blacklist of state to not persist.
  • persistStore takes a Redux store and a persistReducer as input and returns a new store that persists the state to the configured storage.

Here is an example of how to use persistReducer and persistStore:

import { createStore, persistReducer, persistStore } from 'redux-persist';
import { reducer } from './reducers';

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

const persistedReducer = persistReducer(persistConfig, reducer);

const store = createStore(persistedReducer);

const persistor = persistStore(store);

In this example, we are persisting the state of the reducer to the local storage. The key to use to store the state is root. The storage engine to use is localStorage. We are not specifying a whitelist or blacklist, so all of the state will be persisted.

The persistReducer and persistStore functions are used to persist Redux state to persistent storage. This can be useful for storing user preferences, shopping cart items, or other data that should be persisted between app launches.

Here are some of the benefits of using Redux Persist:

  • It allows you to persist your Redux state to persistent storage, so that it is not lost when the app is closed or refreshed.
  • It is easy to use and configure.
  • It supports a variety of storage engines, including localStorage, sessionStorage, and IndexedDB.
  • It is compatible with React and React Native.
728x90

'Frontend > Redux' 카테고리의 다른 글

Redux: PersistGate  (0) 2023.08.20
Redux : toolkit : abort()  (0) 2023.08.20
Redux : createAsyncThunk  (0) 2023.08.20
Redux : toolkit : createAction / createReducer  (0) 2023.08.19
Redux : toolkit API : configureStore()  (0) 2023.08.19
Comments