Part 12 / Topic 3 of 6
React.memo: skip the re-render itself
memo(Component) wraps a component so React can skip calling its function entirely when every prop is === to last time - a different job from useMemo's. examples/03_react_memo_skip_rerender.jsx puts a plain badge and a memoized one side by side, both receiving the identical rating prop, inside a card with unrelated local state:
// examples/03_react_memo_skip_rerender.jsx
export function PlainRatingBadge({ rating }) {
renderCounts.plainBadge++;
return <span>★ {rating}</span>;
}
export const MemoRatingBadge = memo(function MemoRatingBadge({ rating }) {
renderCounts.memoBadge++;
return <span>★ {rating}</span>;
});
export function RestaurantCard({ rating }) {
const [expanded, setExpanded] = useState(false); // unrelated to rating
return (
<div>
<button onClick={() => setExpanded((c) => !c)}>{expanded ? "Hide" : "Show"} details</button>
<PlainRatingBadge rating={rating} />
<MemoRatingBadge rating={rating} />
</div>
);
}
Clicking "Show details" twice - toggling state that rating never touches - really re-renders PlainRatingBadge on both clicks (renderCounts.plainBadge reaches 3: once on mount, once per click), while MemoRatingBadge really stays at its mount-time count of 1 the entire time (examples/03_react_memo_skip_rerender.test.jsx). rating is a plain number here, so it is trivially === across renders - memo had something real to compare, and it worked.
Done here? The practice set for Part 12 — including the solutions — is on the part page.