This library passes the redux store to localStorage.
First install redux persist library to your project:
npm install redux-persist
Then set up redux-persist in your store like so:
import { compose, createStore, applyMiddleware } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import logger from "redux-logger";
const persistConfig = {
key: "root",
storage,
blacklist: ["user"],
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
const middleWares = [logger];
const composedEnhancers = compose(applyMiddleware(...middleWares));
export const store = createStore(
persistedReducer,
undefined,
composedEnhancers
);
export const persistor = persistStore(store);
The above excludes adding the user reducer to persist (blacklist: ["user"]
) because its already being added to the cache.
Now you need to edit your main index.js file to add the PersistGate with the new persist config attached like so:
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/es/integration/react";
import App from "./App";
import { store, persistor } from "./store/store";
import "./index.scss";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<BrowserRouter>
<App />
</BrowserRouter>
</PersistGate>
</Provider>
</React.StrictMode>
);
Now when you refresh your browser you’ll see all the store reducers maintain their state.