React draws a component by calling its function. When a state changes, React draws that component again, and every component inside it. A console.log in a component makes each draw visible: one line per draw, so you can count them.
memo wraps a component so React skips its draw when every prop is the same as last time. Watch out for functions: a function written inside App is a new function on every draw of App, so a card that gets it as a prop always looks changed. useCallback with an empty dependency array [] hands back the same function on every draw.
A color picker could do it like this:
const Swatch = memo(function Swatch({ color, onPick }) {
console.log("draw " + color);
return <button onClick={() => onPick(color)}>{color}</button>;
});
// inside the page component:
const pick = useCallback((color) => setPicked(color), []);
The check opens the page, types p in Search, adds the Pen and clears the search. It must print:
> open the page
console.log: draw Mug
… (one line for each of the 8 products)
console.log: draw Gift card
> type "p" into "Search"
(no draw lines: Mug, Notebook and Gift card leave the list)
> click "Add to cart" in "Pen"
- text: Cart (0)
+ text: Cart (1)
> type "" into "Search"
console.log: draw Mug
console.log: draw Notebook
console.log: draw Gift card
Only the three cards that come back are drawn; the five that stayed are left alone.
Your task: in src/App.jsx, write ProductCard wrapped in memo, with a draw log and its li; make addToCart a useCallback with an empty dependency array; and draw one ProductCard for each shown product.
Assignment
Follow the Coding Tutorial to write a memo card that logs its draws, a stable addToCart, and the list that uses them.
Hint
If the five cards with a p still log a draw when you type, onAdd is still a new function each time: check the [] in useCallback.
Free plan: 30 tutor messages. PRO is unlimited.
