Adding State Persistence to Redux Toolkit Store using Redux Persist
Redux Persist allows you to save (persist) parts of your Redux state to storage (like localStorage or sessionStorage) so that the data remains available even after a page reload. Integrating it with Redux Toolkit is straightforward.
1. Install Redux Persist: Run npm install redux-persist or yarn add redux-persist.
2. Configure Persist Reducer: Use persistReducer() to wrap your root reducer.
3. Create Persistor: Use persistStore() to create a persistor object.
4. Update Store Configuration: Pass the persisted reducer to configureStore().
5. Use PersistGate in React: Wrap your app with PersistGate to delay rendering until the state is rehydrated.
In this example, the user slice state is automatically persisted to localStorage. The serializableCheck is disabled to avoid warnings caused by Redux Persist’s non-serializable objects.
- Selective Persistence: Use the whitelist or blacklist options in persistConfig to control which slices are persisted.
- Storage Options: You can switch to sessionStorage or AsyncStorage (for React Native) as needed.
- Rehydration: PersistGate ensures your app loads the persisted state before rendering.
By combining Redux Toolkit with Redux Persist, you can easily maintain user sessions, preferences, and other important data across browser reloads.