React Redux state is lost at page refresh

My personal advice for hot reloading is using this: React hot loader, this prevents page reload and only switch out the altered chunk. This implies that your state never gets lost while devving.

It is pretty easy to install. You only have to add an entry and wrap your initial component in hot which you can get from the package.

If you need more information on how it works i suggest watching this talk by the creator.


You can use something like redux-persist to save the redux state to local storage or to another storage system.


You can easily persist it in the localstorage. Check the example below.

const loadState = () => {
  try {
    const serializedState = localStorage.getItem('state');
    if(serializedState === null) {
      return undefined;
    }
    return JSON.parse(serializedState);
  } catch (e) {
    return undefined;
  }
};

const saveState = (state) => {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem('state', serializedState);
  } catch (e) {
    // Ignore write errors;
  }
};

const peristedState = loadState();

store.subscribe(() => {
  saveState(store.getState());
});

const store = createStore(
  persistedState,
  // Others reducers...
);

render(
  <Provider store={store}>
    <App/>
  </Provider>,
  document.getElementById('root');
);

Serialization is an expensive operation. You should use a throttle function (like the one implemented by lodash) to limit the number of saves.

Eg:

import throttle from 'lodash/throttle';

store.subscribe(throttle(() => {
  saveState(store.getState());
}, 1000));