Summary
In this lesson, you learned that:
- State is a value that React keeps for a component between renders:
const [likes, setLikes] = useState(0);, withimport { useState } from "react";. A plain variable starts again with every render, and changing it doesn't change the page. - Calling the setter makes React render the component again with the new value and update the page to match. You don't change the page yourself, and you change state only with its setter.
- A component can have several state variables, of any kind: numbers, text, booleans (
setOpen((open) => !open)to show and hide), arrays and objects. What you can compute from state, you compute while rendering. - Each place where a component is used has its own state: three
BandCards, three counters. - The new value comes with the next render. In the handler, the state variable still has the old one. When you need the new one, compute it into a constant first.
- When the new value is computed from the old one, give the setter an updater function:
setLikes((likes) => likes + 1). React calls the queued functions in order, each with the latest value. - Never change state in place. Make a new array or object: add with spread (
[...schedule, id]), remove withfilter(), change one item withmap()and{ ...song, played: true }, and change an object with{ ...ticket, count: 2 }. Afterpush()orticket.count = 2, the state is the same value, and React doesn't render.
In the next lesson, Forms, you'll connect text fields, checkboxes and selects to state, and add new items to a list from a form.
But first, a little practice: a vote for the band of the festival.
Instructions
Put the bands into state, starting with startingBands, and make Vote add 1 to the votes of its band.
Start again sets the votes of all bands back to 0. (map() again, or the starting array.)