Remembering Favorites

In this app, you can mark your favorite bands with a star. But click Run, and the stars are gone: state lives only as long as the page. In the JavaScript course, you kept things like that in localStorage. In React, it takes two steps.

Saving. Writing to localStorage happens outside React, so it's a job for an effect. It should run whenever the favorites change, so its dependency is favorites. localStorage keeps only text, so the array goes in as JSON:

useEffect(() => {
    localStorage.setItem("favorites", JSON.stringify(favorites));
}, [favorites]);

Reading. When the app starts, the favorites should come from localStorage, so that the very first render shows them. The value a state starts with is the argument of useState. But React uses that argument only in the first render, and reading and parsing JSON at every render would be wasted work. So give useState a function instead. React calls it only once, for the first render, and the state starts with what it returns:

const [favorites, setFavorites] = useState(() => {
    const saved = localStorage.getItem("favorites");
    return saved === null ? [] : JSON.parse(saved);
});

getItem() returns null when nothing is saved, for example the first time someone opens the app. Then the favorites start as an empty array.

As in the JavaScript course, each click on Run starts the page again, as a reload does, and the page finds what it saved in earlier runs. The console's button Clear saved data deletes it.

Typical mistakes:

  • Saving the array without JSON.stringify(): localStorage turns it into the text 2,4, which JSON.parse() can't read back.
  • Reading without checking for null: JSON.parse(null) gives null, and favorites.includes() then ends with a TypeError.

Instructions

Save the favorites: add an effect with the dependencies [favorites] that saves them in localStorage under the key favorites, as JSON.

Read them when the app starts: give useState a function that returns the saved favorites, or [] when nothing is saved. Try it: mark two bands and click Run. The stars stay.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

8/9

Next