Hydrate Your Redux Store

Rabah Babaci
3 min readJan 9, 2021

--

A cup of water with a city view on the background

This article will explain the importance of persisting you React JS App state when using Redux.

1.1 Why Even Persist?

When you App reloads, the JavaScript process doesn’t save anything in memory. Your store gets created from scratch and your state is initialized. It is time consuming and expensive to refetch state data every time a page loads. You might also have users with unstable internet connections. Persisting is the first step to offer offline support.

1.2 Why Redux Persist?

Redux Persist takes your Redux state object and saves it to persisted storage. Then on app launch it retrieves this persisted state and saves it back to redux. It provides a consistent, performant, and structured way to persist state.

QuickStart

Redux Persist Installation:

npm install --save redux-persist  -OR-  yarn add redux-persist

Implementation:

You first need to create your Redux Store, pass you createStore function a persistReducer that will wrap the App root reducer. After the store is created, pass it to the persistStore function that will ensure your Redux State is stored to a persisted storage on any changes.

In persistConfig I used the whitelist, which takes an array of strings and each string must match a part of state that is managed by the reducer you passed to persistReducer. For the example above, we would expect ‘userInfo’ to be the rootReducer or was created by using combineReducers function, like so:

The blacklist is set up in the same way as whitelist except that it defines the parts of the state that you do no want to persist.

If you are using ReactJS, wrap you root component with PersistGate. It will allow your App to delay the rendering of the UI until Redux retrieves and saves your persisted state.

Conclusion

And that’s it! Redux Persist is now working in your App and your Redux Store can now be saved on refresh.

I personally think that persisting Redux Store should be done when:

  • You need to keep the history of your modification
  • You often change the form of you store and you have users in production.
  • Local storage of you users are important to be kept.

No one’s perfect. If you’ve found any errors, want to suggest enhancements, or expand on a topic, please feel free to send me a message. I will be sure to include any enhancements or correct any issues.

--

--