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.
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:
- You click Add a cup twice.
- You click Switch to Gyokuro.
- 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…