ReactMedium
What is React.memo?
memo(Component) returns a memoized version of a component that skips re-rendering when its props are shallowly equal to the previous props. It helps when a component re-renders often with the same props and its render is expensive. It does not stop re-renders caused by the component's own state or by contexts it reads.
How it compares props
- Shallow comparison with
Object.isfor each prop. - New object, array or function props break it unless their references are stable (
useMemo,useCallback, constants). - A custom
arePropsEqual(prev, next)can be passed as the second argument, but it is easy to get wrong and can hide bugs.
When it helps
- Rows in large lists where the parent re-renders often.
- Heavy components (charts, editors) beneath frequently updating parents.
- Components whose props are primitives or already stable.
When it does not
- Props change every render anyway.
- The component is cheap to render.
childrenis passed as JSX: a new element object each render means props are never equal.
Still re-renders when
- Its own state changes.
- A context it uses changes.
- Its parent passes new references.
React Compiler
The compiler memoizes components and their JSX automatically, which makes most manual memo usage unnecessary. Components optimized this way show a "Memo ✨" badge in React DevTools.
Code example
tsx
1import { memo, useCallback, useState } from "react";23type RowProps = { id: number; label: string; onSelect: (id: number) => void };45const Row = memo(function Row({ id, label, onSelect }: RowProps) {6 console.log("Row render", id); // logs only when this row's props change7 return <li onClick={() => onSelect(id)}>{label}</li>;8});910export function List({ items }: { items: { id: number; label: string }[] }) {11 const [selected, setSelected] = useState<number | null>(null);12 const [tick, setTick] = useState(0);1314 const onSelect = useCallback((id: number) => setSelected(id), []); // stable, so memo works1516 return (17 <div>18 <button onClick={() => setTick((t) => t + 1)}>Re-render parent ({tick})</button>19 <p>Selected: {selected ?? "none"}</p>20 <ul>21 {items.map((it) => (22 <Row key={it.id} id={it.id} label={it.label} onSelect={onSelect} />23 ))}24 </ul>25 </div>26 );27}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.