10

I’d like to store my app’s state in localStorage. Is there a callback or an event that fires on state change? I would use it to call localStorage.state = JSON.stringify(this.state). Possibly, using 0.5 seconds throttling.

TodoMVC React examples uses localStorage as a storage. However, it defines saving and removing in event handlers such as keydown and click. For my case, doing the same would create a lot of boilerplate.

NVI
  • 14,907
  • 16
  • 65
  • 104

1 Answers1

30

In a componentDidUpdate lifecycle method you could serialize the state:

componentDidUpdate: function(prevProps, prevState) {
    localStorage.state = JSON.stringify(this.state);
}

That code will be run each time the component rerenders (which happens with every props or state change).

Sophie Alpert
  • 139,698
  • 36
  • 220
  • 238
  • 4
    This works nicely for React alone, for anyone trying to do this using React+Flux keep in mind that you need to keep Stores in sync with this as well. In that case you could initialize the state of each Store from localStorage.state, or you could cache each store's data individually. – Adam Stone Jan 31 '15 at 13:02
  • That exactly the issue I have @ http://stackoverflow.com/questions/28375718/who-is-responsible-to-fetch-data-from-server-in-a-flux-app-with-caching – amirouche Feb 20 '15 at 09:32
  • Here's a [fiddle](https://jsfiddle.net/ohujp97v/4/) of this working in a React based TODO MVC example. – Brad Parks Apr 18 '17 at 11:40
  • If you evaluate design options, the next point that will matter is the impact of the performance of `stringify`, which is notoriously famous. You might consider having some logic to reduce the number of `stringify` invocations. Cheers! – Zeena Apr 09 '18 at 04:34