title: How can I save my state to Local Storage in React?
body: <p>I've created functionality for users to add their favorite recipes to a list, they can then view a list of their saved recipes, however I'm trying to get the array of recipes to persist to local storage so the data is not lost on refresh.</p>
  <p>I've saved the data and tried updating the state to what's in the local storage but the data does not persist</p>
  <pre><code>const [myRecipeState, dispatchMyRecipes] = useReducer(myRecipesReducer, {items: []});
  
  const addItemHandler = (item) =&gt; {
      dispatchMyRecipes({val:'ADD', item: item});
    }
  
    const removeItemHandler = (id) =&gt; {
      dispatchMyRecipes({val:'REMOVE', id: id});
    }
  
  const myRecipesReducer = (state, action) =&gt; {
    if (action.val === 'ADD') {
      let updatedItems;
      let updatedItem;
      const existingItemIndex = state.items.findIndex(item =&gt; item.id === action.item.id)
      const existingItem = state.items[existingItemIndex];
      const localRecipes = JSON.parse(localStorage.getItem('myRecipes'));
  
      if (existingItem) {
        updatedItems = [...state.items];
        updatedItem = existingItem;
        updatedItems[existingItemIndex] = updatedItem;
        console.log('item already exists');
        localStorage.setItem('myRecipes', JSON.stringify(updatedItems));
      }else {
        updatedItems = state.items.concat(action.item);
        console.log('item added for the first time');
        localStorage.setItem('myRecipes', JSON.stringify(updatedItems));
      }
      return {items: localRecipes || updatedItems}
    }
  
    if (action.val === 'REMOVE') {
      let updatedItems;
      const localRecipes = JSON.parse(localStorage.getItem('myRecipes'));
      updatedItems = [...state.items].filter(item =&gt; item.id !== action.id);
      localStorage.setItem('myRecipes', JSON.stringify(updatedItems));
      return {items: localRecipes || updatedItemsupdatedItems}
    }
  
    return {items: state.items}
  }
  </code></pre>