Part 12 / Topic 2 of 6
useMemo: cache the calculation, not the render
useMemo(calculate, deps) caches whatever calculate returns, recomputing only when a value in deps changes between renders. examples/02_usememo_expensive_calculation.jsx extracts each row into its own component and wraps the identical calculation:
// examples/02_usememo_expensive_calculation.jsx
function RestaurantRow({ restaurant }) {
const surge = useMemo(() => computeSurgeMultiplier(restaurant.basePrice), [restaurant.basePrice]);
return <li>{restaurant.name}: ×{surge.toFixed(2)}</li>;
}
Typing into the identical delivery-note input now really leaves computeCount.value exactly where it started (examples/02_usememo_expensive_calculation.test.jsx) - zero extra calculations, no matter how many keystrokes. What useMemo did not do: RestaurantRow's function body still runs on every one of those keystrokes (nothing here stops the re-render itself) - it just stopped the expensive line inside it from redoing work whose input, restaurant.basePrice, never actually changed. This distinction - cached calculation vs. skipped render - is the single most common thing to get backwards about useMemo, and it is exactly why Section 3 is a different hook, not a variant of this one.
Done here? The practice set for Part 12 — including the solutions — is on the part page.