Persisting data with localStorage and Redux middleware

Dane Sirois Blocked Unblock Follow Following Aug 29, 2017

LocalStorage is one of many powerful tools at your disposal as a Web Developer. If you need to persist data across sessions, localStorage is a great place to do it. For example, you may wish to persist a theme, or other UI related data so that when a user leaves your app, their experience is saved allowing you to restore from their previous session.

In the following section, I am going to talk about how to use localStorage and where it fits within your application.

Enter Redux middleware:

One implementation that I have found to work well within the context of a Redux application is to do the majority of your localStorage interaction in your Redux middleware. (If you are not familiar with middleware, check out this in-depth article: https://medium.com/@meagle/understanding-87566abcfb7).

Redux middleware allows you to intercept your actions by running them through a block of code before they hit your reducers. This is a great place to interact with localStorage. Simply create a listener for an action and read from its payload to persist data.

> create a listener for an action and read from it’s payload to persist data

Heres an example of intercepting an action to change the app’s current theme:

components/theme_switcher.js:

middleware/CHANGE_THEME.js

In your applications initialize file, you can then configure it to dispatch an action to read the previous theme from localStorage upon connection:

initialize.js

To summarize:

Redux middleware provides a platform for centralizing your use of localStorage and is a powerful way to extend the utility of your actions.

Use localStorage when:

you need to securely persist data you need support across browsers (IE. 8+) you need to cache relatively large datasets (up to 5mb) you want a straightforward API

Use middleware when:

you use Redux you want to centralize your use of localStorage you want to extend the utility of your actions

See more:

https://developer.mozilla.org/en/docs/Web/API/Window/localStorage