How does useMemo optimize component performance?
Hint
useMemo compares its dependencies between renders. What happens if a dependency is a new array every render?
Full Answer
useMemo(fn, deps) caches the result of fn and only recomputes it when a dependency changes (compared with Object.is). It's for expensive calculations and for keeping object or array references stable between renders.
function ProductList({ products, query }) {
// Re-filters only when products or query change
const visible = useMemo(
() => products.filter(p => p.name.includes(query)),
[products, query]
);
// Stable reference so a memoized child can skip re-rendering
const style = useMemo(() => ({ gap: 8 }), []);
return <MemoGrid items={visible} style={style} />;
}
The common mistake: a dependency that's created during render, like const numbers = [1, 2, 3] inside the component, is a new array every time, so the memo recomputes on every render and does nothing. Move constants outside the component or memoize them too.
💡 Don't wrap every value in useMemo — it has its own cost. Reach for it when a calculation is measurably slow or when a stable reference matters (React.memo children, effect dependencies).
More React Fundamentals Questions
Practice this in a timed sprint
5 free questions, no signup required