cf.completefrontend

Predict the outputMedium

This useMemo leaves out a dependency: what does it log and show?

The total is worked out in useMemo, which reads tea and cups but lists only tea as a dependency.

What does it log, and what does the page show?
import { useMemo, useState } from "react";
 
const prices = { Sencha: 4, Gyokuro: 9 };
 
export default function App() {
  const [tea, setTea] = useState("Sencha");
  const [cups, setCups] = useState(1);
 
  const total = useMemo(() => {
    console.log("computing", tea, cups);
    return prices[tea] * cups;
  }, [tea]);
 
  return (
    <>
      <p>
        {cups} cups of {tea}
      </p>
      <p>Total: ${total}</p>
      <button onClick={() => setCups(cups + 1)}>Add a cup</button>
      <button onClick={() => setTea("Gyokuro")}>Switch to Gyokuro</button>
    </>
  );
}

It runs in development, rendered as <App />, and then:

  1. You click Add a cup twice.
  2. You click Switch to Gyokuro.
  3. You click Add a cup once more.

The answer

Work out every line it logs, in order, and what the page shows at the end. Then check.

Checking your sign-in…