How to Synchronize React-Redux with Local storage

UmerFarooq
JavaScript in Plain English
2 min readJun 29, 2021

--

Use local storage to cache API calls for an optimal experience

Introduction:

React Redux is a proven solution when working with React as a global state management system. A lot of companies when hiring ask for Redux combined with React.

Why persist?

Redux is a splendid solution for sharing state amongst your awesome components but more often it faced you with a challenge when opening the application in a new tab or page refresh resulting in loss of state and if not handled properly will result in a blank screen of death in React for nested values.

How to persist?

You can use a couple of solutions to tackle this problem. We can use a custom hook for taking our Redux state and putting that in local storage, but while this approach may have its perks, it’s like reinventing the wheel and could do more harm than good.

My way of persisting?

I use a library going by the name of redux-persist a very famous package with 500K+ weekly downloads its very simple to use, is intuitive, and gets the job done.

// configureStore.js

import { createStore } from 'redux'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web

import rootReducer from './reducers'

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

const persistedReducer = persistReducer(persistConfig, rootReducer)

export default () => {
let store = createStore(persistedReducer)
let persistor = persistStore(store)
return { store, persistor }
}

Basic setup with a few lines of code your store is synchronized with the local storage.

Adding into the app

import { PersistGate } from 'redux-persist/integration/react'

// ... normal setup, create store and persistor, import components etc.

const App = () => {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<RootComponent />
</PersistGate>
</Provider>
);
};

Along with that you could pass the key name to auto increment and deprecate the cache on each build to avoid unwanted mismatches with code and local storage.

With this setup, you can blacklist, whitelist part of your Redux state.

For example, if there is a state you want to update each time you could add that to the blacklist and other logic can also be written to handle as wanted.

As there are multiple APIs provided by the library such as purge flush and more.

Stay tuned for more real-world examples and use-cases as a software engineer.

Peace!

More content at plainenglish.io

--

--

I am a full-stack engineer always curious about how to get things better and in a more productive/ lazy manner. https://umerfarooq.dev