title: How To Update Structure of Redux State Persisted In LocalStorage
body: <p>I save a part of my Redux state in localStorage so that I can persist it across page refreshes.</p>
  
  <p>How do I update the structure of the state in my localStorage if my Redux state structure changes?</p>
  
  <p><br>
  Example:</p>
  
  <p>This is my combineReducer file:</p>
  
  <pre><code>// combineReducer
  
  const rootReducer = combineReducers({
    usersPage: usersPageReducer,
    form: formReducer
  })
  </code></pre>
  
  <p>The original default state in my usersPageReducer looks like:</p>
  
  <pre><code>// usersPageReducer.js
  
  defaultUsersPageState = {
    selectedColumns: ["name", "email"],    
  }
  </code></pre>
  
  <p>I load and save to localStorage using the following methods:</p>
  
  <pre><code>// localStorage.js
  
  export const loadState = () =&gt; {
    try {
      const serializedState = localStorage.getItem('state')
      if (serializedState === null) {
        return undefined;
      }
      return JSON.parse(serializedState)
    } catch (err) {
      return undefined
    }
  }
  
  export const saveState = (state) =&gt; {
    try {
      const serializedState = JSON.stringify(state)
      localStorage.setItem('state', serializedState)
    } catch (err) {
      // to define
    }
  }
  </code></pre>
  
  <p>In my main file, I subscribe to the store, and save the <code>usersPage</code> slice of the state. And I create the store using initial state from localStorage:</p>
  
  <pre><code>// main.js
  const persistedState = loadState();
  const initialState = { ...persistedState };
  
  const store = createStore(
    rootReducer,
    initialState,
  );
  
  store.subscribe(() =&gt; {
    saveState({
      usersPage: store.getState().usersPage
    })
  })
  </code></pre>
  
  <p>Now imagine I want to change my <code>usersPageReducer</code> default state so that it also keeps track of sorting.</p>
  
  <pre><code>// usersPageReducer.js
  
  defaultUsersPageState = {
    selectedColumns: ["name", "email"],
    sorting: {"name": "asc"}   
  }
  </code></pre>
  
  <p>The above won't work because at the start of the app, we hydrate the redux initial state from localStorage. The old initial state beats out the usersPageReducer <code>defaultUsersPageState</code>. </p>
  
  <p>Since localStorage doesn't know about the <code>sorting</code> key for <code>usersPageReducer</code>, and we never use the default state, the <code>sorting</code> key is never added to the redux state.</p>
  
  <p>Is there a way to hydrate the redux store so that it initializes every reducer using it's default state (as if we weren't using localStorage), then spreads the stored state?</p>