Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
React mixin for caching state in sessionStorage across mounts.
var StateCacheMixin = function(key) {
if (!Modernizr.sessionstorage) {
return {};
return {
componentWillMount: function() {
var prevState = sessionStorage.getItem(key);
if (prevState === null) return;
try {
prevState = JSON.parse(prevState);
catch (e) {
if (typeof prevState === 'object') {
componentWillUnmount: function() {
if (this.state !== undefined) {
sessionStorage.setItem(key, JSON.stringify(this.state));
Copy link

Things I don't like: can't use session-stored variables in componentWillMount (as the mixin method apparently gets called after the component), no granularity in choosing which properties to store.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment