Blog>
Snippets

Setting up Redux Persist with Redux Toolkit

Offer a practical example of how to integrate Redux Persist with Redux Toolkit's configureStore to persist and rehydrate the Redux state across sessions.
import { configureStore } from '@reduxjs/toolkit';
import { combineReducers } from 'redux';
import storage from 'redux-persist/lib/storage';
import { persistStore, persistReducer } from 'redux-persist';
import userReducer from './features/user';

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

const rootReducer = combineReducers({
  user: userReducer,
});

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = configureStore({
  reducer: persistedReducer,
});

export const persistor = persistStore(store);
This code imports necessary modules and sets up Redux Persist combined with Redux Toolkit's configureStore. The rootReducer is combined with combineReducers, then enhanced with persistReducer to create a persisted version. The store is then created with configureStore, using the persistedReducer. Finally, persistStore is used to create a persistor that can be used to control the rehydration process.
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { store, persistor } from './store';

// In your root component
function App() {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        {/* Your app's components go here */}
      </PersistGate>
    </Provider>
  );
}
This code snippet shows how to use the store and persistor in a React application. Wrap the entire application with a Provider passing in the store. Within the Provider, wrap your components with PersistGate, which delays the rendering of your app's UI until your persisted state has been retrieved and saved to redux.