What is memoization in React and how do you implement it?
Why Interviewers Ask This
This tests whether you can apply React.js knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
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.
Common Mistake
Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real React.js project.
Previous
What is the difference between useEffect cleanup and componentWillUnmount?
Next
What is the Context API performance issue and how do you fix it?