Use the redux-persist library. It automates saving and rehydrating parts of your Redux store to/from storage (like localStorage). Manually subscribing to the store and using localStorage.setItem/getItem is complex and error-prone.

 What are the Features of Persist specific Redux Slices to localStorage?

  • Handles serialization/deserialization.
  • Supports various storage engines.
  • Allows whitelisting/blacklisting specific slices.
  • Provides transforms and migrations.

Simplified Example (redux-persist Config):

import { configureStore } from '@reduxjs/toolkit';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage'; // localStorage
import rootReducer from './reducers'; // Your combined reducers
const persistConfig = { key: 'root', // Key in localStorage storage, // Storage engine whitelist: ['auth', 'cart'] // ONLY persist these slices // blacklist: ['tempData'] // OR persist everything EXCEPT these
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
// Configure store with persisted reducer
const store = configureStore({ reducer: persistedReducer, // Middleware setup needed to ignore redux-persist actions
});
const persistor = persistStore(store);
// Wrap app in <PersistGate loading={null} persistor={persistor}> in index.js