Computing Instead of Storing

This version of the app has a new button, Clear favorites, and a bug. Try it: star two bands, then click Clear favorites. The stars go out, but the header still says 2.

The app keeps the number of favorites in a second piece of state, count, and every function that changes favorites has to change count too. handleToggleFavorite does, but handleClear forgets. Two pieces of state that have to agree get out of sync as soon as one place forgets one of them.

But the number is already in favorites: it's favorites.length. Don't keep in state what you can compute from other state or props. Work it out while rendering, in the component's function:

const count = favorites.length;

Each render computes it again from the current favorites, so it can't be wrong, whatever changed the array. The same goes for everything else made from your data: totals, filtered lists, whether a list is empty. Only what the user changes needs state, and the rest is computed from it.

A computed value can be a whole list too. Which bands are favorites is a filter of the lineup:

const favoriteBands = bands.filter((band) => favorites.includes(band.id));

And from that, you can compute more, such as the names joined into one text with map() and join().

Instructions

Remove the state count, and compute the number of favorites from favorites instead. Clear favorites then sets the header back to 0 too.

Below the button, show the names of the favorite bands in the order of the lineup, in a paragraph with the class favorite-names: Your favorites: Night Trains, Owl Choir. When there are no favorites, leave the paragraph out.

Start programming for free

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

Or sign up with:

Back

2/6

Next