How can I persist redux state tree on refresh?

incleaf picture incleaf · May 12, 2016 · Viewed 90.7k times · Source

The first principal of Redux documentation is:

The state of your whole application is stored in an object tree within a single store.

And I actually thought that I understand all of principals well. But I'm now confused what does application means.

If application means just one of little complicated part in website and works in just one page, I understand. But what if application means whole website? Should I use LocalStorage or cookie or something for keep the state tree? but what if browser doesn't support LocalStorage?

I want to know how developers keep their state tree! :)

Answer

michaelgmcd picture michaelgmcd · May 12, 2016

If you would like to persist your redux state across a browser refresh, it's best to do this using redux middleware. Check out the redux-persist and redux-storage middleware. They both try to accomplish the same task of storing your redux state so that it may be saved and loaded at will.

--

Edit

It's been some time since I've revisited this question, but seeing that the other (albeit more upvoted answer) encourages rolling your own solution, I figured I'd answer this again.

As of this edit, both libraries have been updated within the last six months. My team has been using redux-persist in production for a few years now and have had no issues.

While it might seem like a simple problem, you'll quickly find that rolling your own solution will not only cause a maintenance burden, but result in bugs and performance issues. The first examples that come to mind are:

  1. JSON.stringify and JSON.parse can not only hurt performance when not needed but throw errors that when unhandled in a critical piece of code like your redux store can crash your application.
  2. (Partially mentioned in the answer below): Figuring out when and how to save and restore your app state is not a simple problem. Do it too often and you'll hurt performance. Not enough, or if the wrong parts of state are persisted, you may find yourself with more bugs. The libraries mentioned above are battle-tested in their approach and provide some pretty fool-proof ways of customizing their behavior.
  3. Part of the beauty of redux (especially in the React ecosystem) is its ability to be placed in multiple environments. As of this edit, redux-persist has 15 different storage implementations, including the awesome localForage library for web, as well as support for React Native, Electron, and Node.

To sum it up, for 3kB minified + gzipped (at the time of this edit) this is not a problem I would ask my team to solve itself.