Updating the Store

Let’s update the store to support persistence.

Next, we add support for persistence to the store. We’ll change our store from this:

import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers/root';
import logMiddleware from './middleware/log';
import apiMiddleware from './middleware/api';

const store = createStore(
  rootReducer,
  applyMiddleware(logMiddleware, apiMiddleware)
);


window.store = store;

export default store;

To this:

import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers/root';
import logMiddleware from './middleware/log';
import apiMiddleware from './middleware/api';
import { persistStore } from 'redux-persist';

const store = createStore(
  rootReducer,
  applyMiddleware(logMiddleware, apiMiddleware)
);

const persistor = persistStore(store);

window.store = store;

export default { store, persistor };

To have our store support persistence, we create a new persistor object wrapping our original store. While we will still use the regular store in our application, the new persistor object allows for more advanced functionality.

With both of these changes done, our store and the browser’s localStorage will automatically sync, and our state will persist across page refreshes.

The redux-persist library has advanced functionality that will allow us to whitelist only part of the state to persist and specify special serializers for states that cannot be serialized with JSON.stringify() (functions, symbols, etc.). We recommend that you review the library’s documentation for details on the more advanced features.

Get hands-on with 1200+ tech skills courses.