Redux Persist
Intermediate
Topic 5 of 20
Redux Persist
Redux Persist is a library that allows saving your Redux store to local storage, ensuring that important application state, such as authentication status or cart contents, survives app restarts.
Installing Redux Persist
bash
npm install redux-persist @react-native-async-storage/async-storage
Configuring Persist
javascript
import AsyncStorage from '@react-native-async-storage/async-storage';
import { persistReducer } from 'redux-persist';
const persistConfig = {
key: 'root',
storage: AsyncStorage,
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
Configuring the Store with Persistence
javascript
import { configureStore } from '@reduxjs/toolkit';
import { persistStore } from 'redux-persist';
export const store = configureStore({ reducer: persistedReducer });
export const persistor = persistStore(store);
Wrapping the App with PersistGate
javascript
import { PersistGate } from 'redux-persist/integration/react';
function App() {
return (
);
}
Persisting Only Specific Reducers
The whitelist and blacklist options in the persist configuration allow you to control exactly which slices of state are saved, avoiding unnecessary persistence of temporary data like loading flags.
javascript
const persistConfig = {
key: 'root',
storage: AsyncStorage,
whitelist: ['auth', 'cart'],
};
Conclusion
Redux Persist ensures your application’s important state remains available even after the app is closed and reopened, providing a seamless experience for features like staying logged in or preserving a shopping cart.