React / 50
React.memo
memo lets a component skip re-rendering when its props haven't changed. Useful for slow components; pointless for cheap ones; often automatic with the React Compiler.
What memo does
import { memo } from "react";
const MenuList = memo(function MenuList({ items }) {
return (
<ul>
{items.map((item) => <li key={item.id}>{item.name}</li>)}
</ul>
);
});
export default MenuList;memo wraps your component and returns a new one. When the parent re-renders, React compares every new prop with the previous one using Object.is (roughly ===). All the same? React skips MenuList and reuses its last output. Anything different? It renders as usual.
trigger
The parent re-renders
plain child
function Row(props)Re-renders
memo child
const Row = memo(function Row(props) …)Skips
Re-renders
Try it. Each badge counts real renders:
Who re-renders?
Try itParent state: 0
renders<Row /> plain
Masala dosa
<MemoRow /> memo(Row)
Masala dosa
Why memo "doesn't work"
The demo's last switch shows the classic trap. Objects, arrays and functions created during render are new every time, even if they look identical:
function Menu({ items }) {
const [query, setQuery] = useState("");
// Both props below are brand-new values on every keystroke:
// a new object and a new function.
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<MenuList
items={items}
options={{ compact: true }}
onSelect={(item) => console.log(item)}
/>
</>
);
}{ compact: true } === { compact: true } is false, so memo sees a changed prop and re-renders on every keystroke. Fix it by keeping the same object between renders: move constants outside the component, or use useMemo and useCallback (next topic).
When to use it (and when not)
| Use memo when… | Skip it when… |
|---|---|
| The component is noticeably slow to render (measure with React DevTools Profiler) | It's small and cheap: the comparison costs about as much as rendering |
| It often re-renders with the same props | Its props change on almost every render anyway |
| Its props are primitives, or objects you keep stable | You'd have to memoize everything around it just to make it work |
Often a better first move costs nothing: move state down into the component that uses it (so fewer things re-render), or pass slow parts as children (JSX passed as children from a parent that didn't re-render keeps the same identity).
Gotchas
Recall
Can you answer these?
0/5
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
