← Back to the exercise

A component's memory

The answer to the exercise in A component's memory.

Both values were ordinary lets. Assigning them changed the variable, but React never redrew the card. A useState pair remembers the value and asks for another render.

import { useState } from "react";
import "./styles.css";
import ShowCard from "./ShowCard";

const shows = [
  { title: "The Bear", year: 2022, genre: "Drama", rating: 8.6, still: "still-warm" },
  { title: "Severance", year: 2022, genre: "Thriller", rating: 8.7, still: "still-cold" },
  { title: "Andor", year: 2022, genre: "Sci-Fi", rating: 8.4, still: "still-dusty" },
];

export default function App() {
  const [watched, setWatched] = useState(false); // was: let watched
  const [index, setIndex] = useState(0); // was: let index
  const show = shows[index];

  function handleWatched() {
    setWatched(true);
  }

  function handleNext() {
    setIndex((index + 1) % shows.length);
  }

  return (
    <div className="page">
      <ShowCard
        title={show.title}
        year={show.year}
        genre={show.genre}
        rating={show.rating}
        still={show.still}
        watched={watched}
        onWatched={handleWatched}
        onNext={handleNext}
      />
    </div>
  );
}