Part 12 / Stage 3
Performance
Goal: Prove a render is genuinely slow before touching a single memoization API, then apply
useMemo,React.memo, anduseCallbackcorrectly, know exactly when memoizing is wasted effort instead of a win, and usekeyto force a clean remount on purpose. Time: ~4 hours ยท Level: comfortable with components, props, and re-renders (Parts 2-3); Part 6's dependency-array reasoning helps
What you will learn
- Why this part opens by measuring, not memoizing: a render counter and a work counter (how many times an expensive calculation actually ran), proving a list is genuinely slow before reaching for any fix - see
DESIGN-NOTES.mdfor why this course teaches memoization dead last, after every state-modeling hook useMemo: caches a calculation's result, keyed on its own dependency array - it does not, by itself, stop the component it's inside from re-rendering at allReact.memo: skips a child's re-render itself when every prop is shallow-equal to last time - a different job fromuseMemo's, often needed together, never interchangeableuseCallback: keeps a function prop stable across renders, which is specifically whatReact.memoneeds to have anything to compare - a memoized child that receives a brand-new inline function every render gets no benefit from being memoized at all- When memoization is actively wasted: a brand-new array/object/function literal passed as a prop defeats
React.memo's shallow comparison just as completely as no memoization at all, while still paying the comparison's cost key-driven remounts: changing an element'skeytells React "this is a different thing, not an update" - forcing a full unmount/mount that resets every bit of that instance's state, which is sometimes exactly the fix a bug needs- This part's running examples: a 200-restaurant list with a genuinely expensive per-row calculation, a rating badge, an order dashboard with click-to-select rows, a menu card's dish tags, and a cart item's note editor
- Every assertion below is a render count or a work count, never a millisecond reading. Wall-clock timing depends on the machine running it and is marked (varies) wherever mentioned in prose, the same convention this course uses everywhere else for non-deterministic output
A note on how this part is organised: same convention as Parts 1-11 - every
examples/andsolutions/file here is wired into this repo's ownharness/and actually executed before being shown below. When you build along, type the code into your own project; this repo's copy is the verified reference, not something you need to open.
Topics in this part
Practice
Every exercise below is a React component (or a Broken/Fixed pair) in its own .jsx file, paired with a .test.jsx that actually renders and interacts with it using Testing Library/Vitest - the same verified-output rule as every example in this course. Every assertion is a render count or a work count (how many times an expensive calculation ran), never a wall-clock timing - the same convention examples/01_slow_list_before_memoization.jsx establishes.
Exercise 1: Prove a slow list, with numbers
Scenario: A BigBasket-style grocery list of 150 items recalculates each item's "final price after today's offer" on every render - including renders caused by an unrelated search box.
What to do: Write GroceryListSlow() with a shared computeCount counter (the same shape as examples/01_slow_list_before_memoization.jsx), a computeFinalPrice(basePrice) function that does real work (a loop) and increments the counter, a 150-item array, and a search <input> whose onChange only updates its own state - nothing an item's price depends on.
Sample output (really run):
mount -> computeCount.value === 150
type one character in search -> computeCount.value === 300 (all 150 recomputed again, for nothing)
๐ก Hint: this is RestaurantListSlow with groceries instead of restaurants - no memoization anywhere yet; the point of this exercise is proving the waste exists, not fixing it.
Exercise 2: Fix Exercise 1 with useMemo
Scenario: Exercise 1's waste, fixed the way Section 2 does.
What to do: Write GroceryListMemoized(): extract each row into its own GroceryRow({ item }) component, and wrap its final-price calculation in useMemo(() => computeFinalPrice(item.basePrice), [item.basePrice]).
Sample output (really run, same search-box interaction as Exercise 1):
mount -> computeCount.value === 150
type one character in search -> computeCount.value still === 150 (no row's basePrice changed)
๐ก Hint: the component still re-renders on every keystroke (nothing here stops that) - only the expensive calculation inside each row is skipped when its own input hasn't changed. Say out loud which one useMemo is actually responsible for before writing the test.
Exercise 3: React.memo alone vs. React.memo + useCallback
Scenario: A food-delivery driver-tracker screen has a list of delivery rows, each with a "mark delivered" button that calls an onMarkDelivered(id) callback. A teammate wrapped the row in memo and called it done.
What to do: Write three versions of the same 40-row list, the same shape as examples/04_usecallback_for_memoized_children.jsx: unmemoized (no memo), memoizedWithInlineCallback (wrapped in memo, but the parent passes (id) => onMarkDelivered(id) written inline on every render), and memoizedWithStableCallback (wrapped in memo, parent passes a useCallback-wrapped function). Each row increments its own renderCounts[...] entry. Drive a re-render with an unrelated piece of parent state (e.g. a "last refreshed" note the user can type into).
Sample output (really run, one unrelated keystroke after mount):
unmemoized: 80 total renders (40 on mount + 40 more)
memoizedWithInlineCallback: 80 total renders (memo found nothing unchanged - no better than no memo at all)
memoizedWithStableCallback: 40 total renders (memo actually skipped the second round)
๐ก Hint: this is examples/04_usecallback_for_memoized_children.jsx's exact shape, renamed - the only thing that should differ between your three versions is whether memo is applied and whether the callback it receives is stable.
Exercise 4: Find and fix a wasted memo
Scenario: A hotel-booking results card shows a list of amenity tags (["AC", "WiFi", "Breakfast"]) via a memo-wrapped AmenityTags component. A reviewer suspects the memo is doing nothing.
What to do: Write HotelCardWasted(), passing AmenityTags a fresh array literal on every render (the same mistake as examples/05_memoization_wasted.jsx's memoWithInlineProp), and HotelCardFixed(), passing the same tags via a reference declared once outside the component (or wrapped in its own useMemo). Prove the difference with a render count, driven by an unrelated keystroke in the card.
Sample output (really run, two unrelated keystrokes after mount):
HotelCardWasted: AmenityTags rendered 3 times total - identical to having no memo at all
HotelCardFixed: AmenityTags rendered 1 time total - the stable reference let memo actually skip
๐ก Hint: the array's contents never change in either version - only the reference does in the broken one. memo's shallow comparison only ever looks at the reference, never the contents.
Exercise 5: Reproduce and fix a key-driven state leak
Scenario: A job-application tracker shows a notes textarea for whichever application is currently selected. A teammate's version swaps which application's data is shown without changing any key.
What to do: Write ApplicationNotesBroken({ application }) and ApplicationNotesFixed({ application }), the same shape as examples/06_key_driven_remount.jsx's CartItemEditorBroken/Fixed - an internal draft state initialized from application.savedNotes, and a shared mountCount counter incremented inside a useEffect(() => { mountCount.value++; }, []). Only the fixed version's wrapper passes key={application.id} to the inner note-editing component.
Sample output (really run - render with application A, type a draft, then switch to application B):
ApplicationNotesBroken: mountCount stays at 1 (same instance reused); application B's editor shows application A's leftover draft
ApplicationNotesFixed: mountCount reaches 2 (a real remount happened); application B's editor starts with its own saved notes
๐ก Hint: the bug and the fix live entirely in the parent - whether it passes a key tied to application.id - not in the inner editing component itself, which can be identical in both versions.
Exercise 6: A fully memoized dashboard, built from scratch
Scenario: An e-commerce seller dashboard shows a list of 100 products, each with a genuinely expensive "demand score" calculation and a "feature this product" button, alongside an unrelated "dashboard note" field and an unrelated live order counter that increments on a timer.
What to do: Build this dashboard from nothing, applying every technique in this part deliberately: a shared computeCount for the demand-score calculation, useMemo to cache each product's score keyed on the product's own data, React.memo on the row component, useCallback for the "feature this product" callback passed to each row, and a render-count object proving the timer-driven order counter's ticking does not recompute a single demand score or re-render a single row.
Sample output (really run - mount, then advance a fake timer by 3 "ticks" of the live order counter):
mount -> computeCount.value === 100, every row rendered once
3 order-counter ticks -> computeCount.value still === 100, every row's render count still at 1
(only the order-counter text itself updated on screen)
๐ก Hint: this is every earlier exercise in this part combined into one component tree - build it section by section (measure the naive version first if you want the full before/after proof) rather than trying to get every hook right in one pass. vi.useFakeTimers() plus vi.advanceTimersByTime(...) drives the "ticks" deterministically, the same convention examples/02_live_clock_cleanup.test.jsx (Part 6) uses for a repeating timer.
Show the solutions for Part 12 (12 files)
solutions/ex01_grocery_list_slow.jsx
// Exercise 1 solution: same shape as
// examples/01_slow_list_before_memoization.jsx - no memoization anywhere,
// so every item recomputes its final price on every render, including
// renders caused by the unrelated search box.
import { useState } from "react";
export const computeCount = { value: 0 };
export function computeFinalPrice(basePrice) {
computeCount.value++;
let total = 0;
for (let i = 0; i < 20000; i++) {
total += Math.sqrt(basePrice + i) % 7;
}
return basePrice - (total % 30);
}
export const GROCERIES = Array.from({ length: 150 }, (_, i) => ({
id: `G-${i}`,
name: `Item ${i}`,
basePrice: 50 + i,
}));
export function GroceryListSlow() {
const [search, setSearch] = useState("");
return (
<div>
<input aria-label="search groceries" value={search} onChange={(e) => setSearch(e.target.value)} />
<ul>
{GROCERIES.map((item) => {
const finalPrice = computeFinalPrice(item.basePrice);
return (
<li key={item.id}>
{item.name}: โน{finalPrice}
</li>
);
})}
</ul>
</div>
);
}
solutions/ex01_grocery_list_slow.test.jsx
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it } from "vitest";
import { computeCount, GROCERIES, GroceryListSlow } from "./ex01_grocery_list_slow.jsx";
beforeEach(() => {
computeCount.value = 0;
});
describe("GroceryListSlow recomputes every item's final price on every render", () => {
it("really runs the calculation once per item on mount", () => {
render(<GroceryListSlow />);
expect(computeCount.value).toBe(GROCERIES.length);
});
it("really reruns the calculation for every item on a keystroke in the unrelated search box", () => {
render(<GroceryListSlow />);
fireEvent.change(screen.getByLabelText("search groceries"), { target: { value: "r" } });
expect(computeCount.value).toBe(GROCERIES.length * 2);
});
});
solutions/ex02_grocery_list_memoized.jsx
// Exercise 2 solution: fixes Exercise 1 the way
// examples/02_usememo_expensive_calculation.jsx does - useMemo caches the
// calculation per row, keyed on that row's own basePrice.
import { useMemo, useState } from "react";
export const computeCount = { value: 0 };
export function computeFinalPrice(basePrice) {
computeCount.value++;
let total = 0;
for (let i = 0; i < 20000; i++) {
total += Math.sqrt(basePrice + i) % 7;
}
return basePrice - (total % 30);
}
export const GROCERIES = Array.from({ length: 150 }, (_, i) => ({
id: `G-${i}`,
name: `Item ${i}`,
basePrice: 50 + i,
}));
function GroceryRow({ item }) {
const finalPrice = useMemo(() => computeFinalPrice(item.basePrice), [item.basePrice]);
return (
<li>
{item.name}: โน{finalPrice}
</li>
);
}
export function GroceryListMemoized() {
const [search, setSearch] = useState("");
return (
<div>
<input aria-label="search groceries" value={search} onChange={(e) => setSearch(e.target.value)} />
<ul>
{GROCERIES.map((item) => (
<GroceryRow key={item.id} item={item} />
))}
</ul>
</div>
);
}
solutions/ex02_grocery_list_memoized.test.jsx
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it } from "vitest";
import { computeCount, GROCERIES, GroceryListMemoized } from "./ex02_grocery_list_memoized.jsx";
beforeEach(() => {
computeCount.value = 0;
});
describe("GroceryListMemoized skips recomputation when basePrice hasn't changed", () => {
it("really runs the calculation once per item on mount", () => {
render(<GroceryListMemoized />);
expect(computeCount.value).toBe(GROCERIES.length);
});
it("really does NOT rerun the calculation on an unrelated keystroke", () => {
render(<GroceryListMemoized />);
fireEvent.change(screen.getByLabelText("search groceries"), { target: { value: "r" } });
expect(computeCount.value).toBe(GROCERIES.length);
});
});
solutions/ex03_delivery_tracker.jsx
// Exercise 3 solution: same shape as
// examples/04_usecallback_for_memoized_children.jsx - three parallel
// lists of the same rows, differing only in whether memo is applied and
// whether the callback it receives is stable.
//
// This is demonstration code, not a pattern to copy: mutating a
// module-level object during render (renderCounts[countKey]++ below) is
// how this exercise proves a render happened at all, and oxlint
// genuinely flags it - `react(immutability): This value cannot be
// modified`. That warning is correct; a real app counts renders with
// React DevTools' Profiler instead.
import { memo, useCallback, useState } from "react";
export const renderCounts = {
unmemoized: 0,
memoizedWithInlineCallback: 0,
memoizedWithStableCallback: 0,
};
function DeliveryRowImpl({ delivery, onMarkDelivered, countKey }) {
renderCounts[countKey]++;
return (
<li>
{delivery.id}
<button onClick={() => onMarkDelivered(delivery.id)}>Mark delivered</button>
</li>
);
}
const MemoDeliveryRow = memo(DeliveryRowImpl);
export const DELIVERIES = Array.from({ length: 40 }, (_, i) => ({ id: `DEL-${i}` }));
export function DeliveryTrackerDashboard() {
const [lastRefreshed, setLastRefreshed] = useState("");
const [, setDeliveredId] = useState(null);
const markInline = (id) => setDeliveredId(id);
const markStable = useCallback((id) => setDeliveredId(id), []);
return (
<div>
<input
aria-label="last refreshed note"
value={lastRefreshed}
onChange={(e) => setLastRefreshed(e.target.value)}
/>
<ul aria-label="unmemoized">
{DELIVERIES.map((d) => (
<DeliveryRowImpl key={d.id} delivery={d} onMarkDelivered={markInline} countKey="unmemoized" />
))}
</ul>
<ul aria-label="memoized, inline callback">
{DELIVERIES.map((d) => (
<MemoDeliveryRow
key={d.id}
delivery={d}
onMarkDelivered={markInline}
countKey="memoizedWithInlineCallback"
/>
))}
</ul>
<ul aria-label="memoized, stable callback">
{DELIVERIES.map((d) => (
<MemoDeliveryRow
key={d.id}
delivery={d}
onMarkDelivered={markStable}
countKey="memoizedWithStableCallback"
/>
))}
</ul>
</div>
);
}
solutions/ex03_delivery_tracker.test.jsx
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it } from "vitest";
import { DELIVERIES, DeliveryTrackerDashboard, renderCounts } from "./ex03_delivery_tracker.jsx";
beforeEach(() => {
renderCounts.unmemoized = 0;
renderCounts.memoizedWithInlineCallback = 0;
renderCounts.memoizedWithStableCallback = 0;
});
describe("memo only pays off once the callback it receives is stable", () => {
it("really renders every row once per list on mount", () => {
render(<DeliveryTrackerDashboard />);
expect(renderCounts.unmemoized).toBe(DELIVERIES.length);
expect(renderCounts.memoizedWithInlineCallback).toBe(DELIVERIES.length);
expect(renderCounts.memoizedWithStableCallback).toBe(DELIVERIES.length);
});
it("really re-renders the unmemoized and inline-callback rows on an unrelated keystroke, but not the stable-callback rows", () => {
render(<DeliveryTrackerDashboard />);
fireEvent.change(screen.getByLabelText("last refreshed note"), { target: { value: "n" } });
expect(renderCounts.unmemoized).toBe(DELIVERIES.length * 2);
expect(renderCounts.memoizedWithInlineCallback).toBe(DELIVERIES.length * 2);
expect(renderCounts.memoizedWithStableCallback).toBe(DELIVERIES.length);
});
});
solutions/ex04_hotel_card.jsx
// Exercise 4 solution: same shape as examples/05_memoization_wasted.jsx -
// the amenity tags' CONTENTS never change in either version, only the
// WASTED version's array REFERENCE changes on every render, which is all
// memo's shallow comparison actually looks at.
//
// This is demonstration code, not a pattern to copy: mutating a
// module-level object during render (renderCounts[countKey]++ below) is
// how this exercise proves a render happened at all, and oxlint
// genuinely flags it - `react(immutability): This value cannot be
// modified`. That warning is correct; a real app counts renders with
// React DevTools' Profiler instead.
import { memo, useState } from "react";
export const renderCounts = { wasted: 0, fixed: 0 };
export const AmenityTags = memo(function AmenityTags({ amenities, countKey }) {
renderCounts[countKey]++;
return <span>{amenities.join(", ")}</span>;
});
const STABLE_AMENITIES = ["AC", "WiFi", "Breakfast"];
export function HotelCardWasted() {
const [note, setNote] = useState("");
return (
<div>
<input aria-label="hotel note" value={note} onChange={(e) => setNote(e.target.value)} />
<AmenityTags amenities={["AC", "WiFi", "Breakfast"]} countKey="wasted" />
</div>
);
}
export function HotelCardFixed() {
const [note, setNote] = useState("");
return (
<div>
<input aria-label="hotel note" value={note} onChange={(e) => setNote(e.target.value)} />
<AmenityTags amenities={STABLE_AMENITIES} countKey="fixed" />
</div>
);
}
solutions/ex04_hotel_card.test.jsx
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it } from "vitest";
import { HotelCardFixed, HotelCardWasted, renderCounts } from "./ex04_hotel_card.jsx";
beforeEach(() => {
renderCounts.wasted = 0;
renderCounts.fixed = 0;
});
describe("memo is wasted on HotelCardWasted's recreated array prop", () => {
it("really re-renders on every keystroke, identical to having no memo at all", () => {
render(<HotelCardWasted />);
const input = screen.getByLabelText("hotel note");
fireEvent.change(input, { target: { value: "n" } });
fireEvent.change(input, { target: { value: "ni" } });
expect(renderCounts.wasted).toBe(3);
});
});
describe("memo actually skips on HotelCardFixed's stable array reference", () => {
it("really stays at its mount-time render count through the same keystrokes", () => {
render(<HotelCardFixed />);
const input = screen.getByLabelText("hotel note");
fireEvent.change(input, { target: { value: "n" } });
fireEvent.change(input, { target: { value: "ni" } });
expect(renderCounts.fixed).toBe(1);
});
});
solutions/ex05_application_notes.jsx
// Exercise 5 solution: same shape as examples/06_key_driven_remount.jsx -
// the bug and the fix live entirely in whether the wrapper passes a key
// tied to the application's identity; the inner editor is identical.
import { useEffect, useState } from "react";
export const mountCount = { value: 0 };
function NotesEditor({ applicationId, initialNotes }) {
const [draft, setDraft] = useState(initialNotes);
useEffect(() => {
mountCount.value++;
}, []);
return (
<div>
<p>Notes for {applicationId}</p>
<textarea
aria-label={`notes-${applicationId}`}
value={draft}
onChange={(e) => setDraft(e.target.value)}
/>
</div>
);
}
export function ApplicationNotesBroken({ application }) {
return <NotesEditor applicationId={application.id} initialNotes={application.savedNotes} />;
}
export function ApplicationNotesFixed({ application }) {
return (
<NotesEditor key={application.id} applicationId={application.id} initialNotes={application.savedNotes} />
);
}
solutions/ex05_application_notes.test.jsx
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it } from "vitest";
import { ApplicationNotesBroken, ApplicationNotesFixed, mountCount } from "./ex05_application_notes.jsx";
const APPLICATION_A = { id: "app-A", savedNotes: "" };
const APPLICATION_B = { id: "app-B", savedNotes: "" };
beforeEach(() => {
mountCount.value = 0;
});
describe("ApplicationNotesBroken reuses the same instance across applications", () => {
it("really leaks application A's draft into application B's editor", () => {
const { rerender } = render(<ApplicationNotesBroken application={APPLICATION_A} />);
expect(mountCount.value).toBe(1);
fireEvent.change(screen.getByLabelText("notes-app-A"), {
target: { value: "strong candidate, follow up Monday" },
});
rerender(<ApplicationNotesBroken application={APPLICATION_B} />);
expect(mountCount.value).toBe(1);
expect(screen.getByLabelText("notes-app-B")).toHaveValue("strong candidate, follow up Monday");
});
});
describe("ApplicationNotesFixed forces a remount via a key tied to application.id", () => {
it("really resets to application B's own saved notes", () => {
const { rerender } = render(<ApplicationNotesFixed application={APPLICATION_A} />);
expect(mountCount.value).toBe(1);
fireEvent.change(screen.getByLabelText("notes-app-A"), {
target: { value: "strong candidate, follow up Monday" },
});
rerender(<ApplicationNotesFixed application={APPLICATION_B} />);
expect(mountCount.value).toBe(2);
expect(screen.getByLabelText("notes-app-B")).toHaveValue("");
});
});
solutions/ex06_seller_dashboard.jsx
// Exercise 6 solution: every technique in this part combined - useMemo
// for the per-row expensive calculation, React.memo on the row, a
// useCallback-stabilized callback so memo has something real to compare,
// and a completely unrelated ticking timer that proves none of it
// recomputes or re-renders a single row.
//
// This is demonstration code, not a pattern to copy: mutating a
// module-level object during render (renderCounts.row++ below) is how
// this exercise proves a render happened at all, and oxlint genuinely
// flags it - `react(immutability): This value cannot be modified`. That
// warning is correct; a real app counts renders with React DevTools'
// Profiler instead.
import { memo, useCallback, useEffect, useMemo, useState } from "react";
export const computeCount = { value: 0 };
export const renderCounts = { row: 0 };
export function computeDemandScore(basePrice) {
computeCount.value++;
let total = 0;
for (let i = 0; i < 20000; i++) {
total += Math.sqrt(basePrice + i) % 7;
}
return total % 100;
}
export const PRODUCTS = Array.from({ length: 100 }, (_, i) => ({
id: `P-${i}`,
name: `Product ${i}`,
basePrice: 100 + i,
}));
const ProductRow = memo(function ProductRow({ product, onFeature }) {
renderCounts.row++;
const demandScore = useMemo(() => computeDemandScore(product.basePrice), [product.basePrice]);
return (
<li>
{product.name}: demand {demandScore}
<button onClick={() => onFeature(product.id)}>Feature</button>
</li>
);
});
export function SellerDashboard() {
const [note, setNote] = useState("");
const [orderCount, setOrderCount] = useState(0);
const [, setFeaturedId] = useState(null);
// Completely unrelated to any product - ticks on its own timer.
useEffect(() => {
const intervalId = setInterval(() => setOrderCount((c) => c + 1), 1000);
return () => clearInterval(intervalId);
}, []);
const handleFeature = useCallback((id) => setFeaturedId(id), []);
return (
<div>
<input aria-label="dashboard note" value={note} onChange={(e) => setNote(e.target.value)} />
<p>Live orders: {orderCount}</p>
<ul>
{PRODUCTS.map((product) => (
<ProductRow key={product.id} product={product} onFeature={handleFeature} />
))}
</ul>
</div>
);
}
solutions/ex06_seller_dashboard.test.jsx
import { act, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { computeCount, PRODUCTS, renderCounts, SellerDashboard } from "./ex06_seller_dashboard.jsx";
beforeEach(() => {
computeCount.value = 0;
renderCounts.row = 0;
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
describe("SellerDashboard's ticking order counter never touches the product rows", () => {
it("really computes each row's demand score exactly once on mount", () => {
render(<SellerDashboard />);
expect(computeCount.value).toBe(PRODUCTS.length);
expect(renderCounts.row).toBe(PRODUCTS.length);
});
it("really leaves every row's render and compute count unchanged after the order counter ticks", () => {
render(<SellerDashboard />);
act(() => {
vi.advanceTimersByTime(3000);
});
expect(screen.getByText("Live orders: 3")).toBeInTheDocument();
expect(computeCount.value).toBe(PRODUCTS.length);
expect(renderCounts.row).toBe(PRODUCTS.length);
});
});
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Reaching for useMemo/useCallback/React.memo before measuring anything |
Premature memoization adds real complexity (and a real comparison cost) for a problem that was never measured to exist - this course's most emphasized performance mistake | Count renders and/or the work an expensive calculation does first; only memoize what a real count just proved is wasted (Section 1) |
Assuming useMemo stops a component from re-rendering |
useMemo only caches a calculation's result; the component's function body still runs on every render that reaches it |
Use React.memo for "skip the re-render itself"; use useMemo for "skip recomputing something whose inputs didn't change" - they answer different questions (Section 2-3) |
Wrapping a component in React.memo while still passing it an inline arrow function, array, or object literal as a prop |
A new literal is never === to the previous one, so memo's shallow comparison never finds anything unchanged - it skips nothing, for the same comparison cost as if it worked |
Keep every prop passed to a memoized component referentially stable across renders - useCallback for functions, a module-level constant or useMemo for arrays/objects (Section 4-5) |
Treating memo as something that is always a net win to add |
memo's shallow comparison is not free; on a component that was never going to be a measured problem, or one whose props always change anyway, it is pure overhead with nothing to show for it |
Memoize where a real render/work count justified it (Section 1), not reflexively on every component |
Not realizing a changed key forces a full remount |
Switching what a component instance represents (a different list item, a different form target) while keeping the same key lets React silently reuse stale internal state across two different things |
Give a component a key tied to the identity of the thing it represents whenever reusing state across that change would be wrong (Section 6) |
Quick recap
- Measure before memoizing: a render count and a work count (how many times an expensive calculation actually ran) are this course's deterministic stand-ins for "how slow was this" - wall-clock milliseconds vary by machine and are never asserted on directly.
useMemocaches a calculation's result, keyed on its own dependency array; it does not stop the component it's inside from re-rendering.React.memoskips a child's re-render itself when every prop is shallow-equal to last time - a different job fromuseMemo's, and the two are frequently needed together.useCallbackkeeps a function prop's reference stable across renders - specifically so amemo-wrapped child that receives it has something real to compare; without it,memogets no benefit from wrapping that child at all.- Any prop recreated as a new array/object/function literal on every render defeats
memoexactly as completely as not memoizing, while still paying the comparison's cost - memoizing is not automatically a win. - A changed
keytells React "this is a different thing, not an update," forcing a genuine unmount/mount that resets all of that instance's state - the deliberate opposite ofmemo's "reuse this instance."
Checklist
- I can say, in one sentence, why this part counts renders and expensive-calculation calls instead of measuring milliseconds.
- I built (or ran) a list whose per-row calculation is genuinely expensive, proved an unrelated state change recomputes every row, and can say exactly how many extra calculations that cost.
- I can explain, without looking it up, the exact difference between what
useMemoskips and whatReact.memoskips. - I reproduced the "memoized child, inline callback" mistake myself - wrapped a component in
memo, passed it an inline arrow function, and proved via a render count thatmemodid nothing - then fixed it withuseCallback. - I found (or wrote) a case of
memobeing wasted because of a recreated array/object/function prop, and proved the render count was identical with or without thememowrapper. - I reproduced the key-driven-remount bug myself - state leaking across a component reused for a different underlying item - then fixed it by giving the component a
keytied to that item's identity, and confirmed a real remount happened via a mount counter.