What does React.memo do, and when does it fail to help?
React.memo wraps a component so React skips re-rendering it when its props are shallowly equal to the last render. It fails when you pass new object, array or function references on every parent render.
Explain it simply
React.memo is a bouncer with a photograph of your last props. If the new props match, the component is not called again. The match is shallow: each prop is compared with Object.is.
The catch is that {}, [] and () => {} written inline in JSX create a new reference each render, so the bouncer sees a stranger every time and the memo never skips.
Fix this by creating stable references with useMemo and useCallback, or move the constant outside the component. Also note that a memoised component still re-renders when its own state changes or a context it reads changes.
Example
const Chart = React.memo(function Chart({ data, options }) {
return <canvas />;
});
function Dashboard({ rows }) {
// new object each render: memo is useless
return <Chart data={rows} options={{ color: "blue" }} />;
}
const OPTIONS = { color: "blue" }; // stable reference, memo worksWhat to say in the interview
"React.memo skips a re-render when props are shallowly equal. It only helps if the props are stable, so inline objects, arrays and functions defeat it unless I memoise them. I use it for components that render often with the same props and cost real time, and I check with the Profiler first."
Common mistakes
- Wrapping every component in memo without measuring.