⚛️ React.js Intermediate

What is memoization in React and how do you implement it?

Answer

Memoization in React is the optimization of caching computed values or component renders to avoid expensive recalculation when inputs have not changed. Three tools: (1) React.memo(Component): memoizes a component — skips re-rendering if props have not changed (shallow comparison). For components that receive the same props often. (2) useMemo(() => computation, [deps]): memoizes a computed value — only recomputes when dependencies change. For expensive calculations within a component. (3) useCallback(fn, [deps]): memoizes a function reference — returns the same function object unless dependencies change. For stable callback references to pass to memoized children or useEffect deps. Memoization is NOT always beneficial: each memoization has overhead (memory, comparison cost). For cheap computations and non-memoized children, the overhead exceeds the benefit. Profile first with React DevTools Profiler to identify actual bottlenecks before adding memoization. Common mistake: memoizing everything — this clutters code and can actually hurt performance. Profile, measure, optimize selectively.