1 min read

Check your work: Add persistence to local storage for an existing app

💡
This is a detailed tutorial that solves the Add persistence to local storage for an existing app exercise.
If you haven't already, try to solve it yourself first before reading the solution!

Here's the completed exercise: https://codesandbox.io/p/sandbox/shopping-list-local-storage-solution-rghxn7

Did you solve it the same way? Check your work by going over the questions below.

How are you initialising the data?

  • Data is not loaded from localStorage on page load - 0 points
  • Using useEffect - 1 point
  • Using useState initial value - 2 points

Using useEffect to load the data from localStorage into the state works, but it causes an extra render and makes the code harder to read.
A simpler option is to simply use the useState initial value:

const [list, setList] = useState(JSON.parse(localStorage.getItem('items')));

Alternatively, you can use the function setter.

const [list, setList] = useState(() => JSON.parse(localStorage.getItem('items')) || []);

If you want to dive deeper, check out these two articles:

How are you saving the user changes to local storage?

  • Data is not saved to localStorage after user changes the shopping list - 0 points
  • Using useEffect - 1 point
  • Directly in the event handler - 2 points

One way to sync the data to local storage is to have a useEffect hook that triggers everytime the list changes. This works but is actually an anti-pattern.

useEffect(() => {
    localStorage.setItem('items', JSON.stringify(list));
}, [list]);

A better way is to update the local storage directly in the event handler that updates the list.

 const handleAddItem = (e) => {
    e.preventDefault();
    if (newItem === "") {
      return;
    }
    setShoppingList(items);
    window.localStorage.setItem("shoppingList", JSON.stringify(items));
    setNewItem("");
  };