Blog>
Snippets

Implementing State Persistence

Illustrate how to persist and rehydrate the store's state using local storage to maintain application state between sessions.
const saveState = (state) => {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem('state', serializedState);
  } catch (err) {
    console.error('Could not save state', err);
  }
};
This function serializes the state object into a string using JSON.stringify and saves it to local storage under the key 'state'. It wraps the operation in a try/catch block to handle potential errors, such as when local storage is full.
const loadState = () => {
  try {
    const serializedState = localStorage.getItem('state');
    if (serializedState === null) {
      return undefined; // Local storage is empty
    }
    return JSON.parse(serializedState);
  } catch (err) {
    return undefined; // Failed to read from local storage
  }
};
This function attempts to retrieve the state from local storage. If it finds a serialized state, it parses it back into an object using JSON.parse. If the state is not found or an error occurs during retrieval, it returns undefined. This can be used to initialize the store to its default state.
// Example of using saveState and loadState with a Redux store
import { createStore } from 'redux';
const persistedState = loadState();
const store = createStore(
  rootReducer,
  persistedState // Use the loaded state as the initial state
);

store.subscribe(() => {
  saveState(store.getState());
});
This snippet demonstrates how to integrate the saveState and loadState functions with a Redux store. It loads the persisted state from local storage and uses it as the initial state for the Redux store. Then it subscribes to the store, and on each state update, it saves the new state back to local storage, ensuring that the application's state is persisted across sessions.