Each Card Has Its Own State
Where does React keep state? Not in the function, which runs anew on every render. React keeps it for the component at its place on the page. So when a component is used three times, each of the three has its own state.
Here's a BandCard with a like button, in a file of its own:
import { useState } from "react";
export default function BandCard({ name }) {
const [likes, setLikes] = useState(0);
return (
<li className="card">
<h2>{name}</h2>
<button onClick={() => setLikes(likes + 1)}>♥ {likes}</button>
</li>
);
}And App shows three of them:
<ul>
<BandCard name="Night Trains" />
<BandCard name="Lunar Cats" />
<BandCard name="Owl Choir" />
</ul>Click the heart of Lunar Cats twice, and only its card shows ♥ 2. The other two still show ♥ 0. Each BandCard has its own likes, even though they all come from the same function, just as three copies of a form are filled in separately. (The handler here is a single short line, so it's written right in the JSX.)
When the cards come from map(), React tells them apart by their key. That's one more reason for keys from ids: when the list changes, each band keeps its own likes.
State is private to its component. App doesn't know how many likes a card has, and the cards don't know about each other. What if App needed the numbers, say to show all the likes together? Then the state would have to move up into App. That's what the Sharing State lesson is about, later in the course.
Instructions
In BandCard.jsx, give the card a state likes, and make a click on the heart add 1 to it. The button shows ♥ and the number. Try a few cards: each one counts on its own.
Give the card a second state, favorite: a click on ☆ changes it to ★, and another click back to ☆. Again, each card has its own.