React useMemo Interview Guide
What is useMemo?
Section titled “What is useMemo?”useMemo is a React Hook used to memoize (cache) the result of an expensive computation and recompute it only when its dependencies change.
const memoizedValue = useMemo(() => { return expensiveCalculation(data);}, [data]);Benefit: Improves performance by avoiding unnecessary recalculations during re-renders.
Why do we need useMemo?
Section titled “Why do we need useMemo?”Without useMemo, expensive calculations execute on every render.
const total = calculateTotal(items); // Runs every renderWith useMemo:
const total = useMemo(() => calculateTotal(items), [items]);Now calculateTotal() runs only when items changes.
How useMemo Works
Section titled “How useMemo Works”flowchart TD
A[Component Renders] --> B{Dependencies Changed?}
B -->|Yes| C[Run Calculation]
C --> D[Cache Result]
D --> E[Return Memoized Value]
B -->|No| E
useMemo vs useCallback
Section titled “useMemo vs useCallback”| useMemo | useCallback |
|---|---|
| Memoizes a value | Memoizes a function |
| Returns computed result | Returns function reference |
| Used for expensive calculations | Used to prevent function recreation |
const total = useMemo(() => sum(items), [items]);
const handleClick = useCallback(() => { console.log("Clicked");}, []);When Should You Use useMemo?
Section titled “When Should You Use useMemo?”Use it when:
- Expensive calculations exist.
- Large list filtering/sorting.
- Prevent unnecessary re-computations.
- Derived state calculations.
Example:
const filteredUsers = useMemo(() => { return users.filter(user => user.active);}, [users]);Can useMemo Prevent Component Re-rendering?
Section titled “Can useMemo Prevent Component Re-rendering?”No.
It only memoizes a value.
A component still re-renders when:
- State changes
- Props change
- Parent re-renders
For preventing re-renders, use:
React.memo()Dependency Array Behavior
Section titled “Dependency Array Behavior”Empty Dependency Array
Section titled “Empty Dependency Array”const result = useMemo(() => calculate(), []);Runs only during the initial render. Future dependency changes are ignored, which can lead to stale data.
No Dependency Array
Section titled “No Dependency Array”const result = useMemo(() => calculate());Runs on every render, providing no memoization benefit.
Dependency Comparison
Section titled “Dependency Comparison”React performs a shallow comparison on dependency values.
useMemo(() => calculate(), [count]);- Different values (e.g.,
countgoes from1to2): recalculates - Same value (e.g.,
countstays1): returns cached value
Expensive Computation Example
Section titled “Expensive Computation Example”Without useMemo:
const factorial = (n) => { console.log("Calculating"); return n <= 1 ? 1 : n * factorial(n - 1);};
const result = factorial(number);With useMemo:
const result = useMemo(() => { return factorial(number);}, [number]);Does useMemo Always Improve Performance?
Section titled “Does useMemo Always Improve Performance?”No.
Memoization has memory and dependency comparison overhead.
Avoid using it for simple calculations such as:
const fullName = firstName + lastName;Large List Example
Section titled “Large List Example”const sortedProducts = useMemo(() => { return products.sort((a, b) => a.price - b.price);}, [products]);useMemo vs React.memo
Section titled “useMemo vs React.memo”| useMemo | React.memo |
|---|---|
| Memoizes value | Memoizes component |
| Hook | Higher Order Component |
| Inside component | Wraps component |
const Child = React.memo(({name}) => { return <h1>{name}</h1>;});API Calls
Section titled “API Calls”useMemo should not be used for API calls.
Use useEffect instead.
useEffect(() => { fetchUsers();}, []);Lifecycle
Section titled “Lifecycle”- Initial render -> calculation executes.
- Result is cached.
- Component re-renders.
- Dependencies unchanged -> cached value returned.
- Dependencies changed -> recalculation occurs.
Memoizing Objects
Section titled “Memoizing Objects”Without useMemo:
const config = { theme: "dark"};With useMemo:
const config = useMemo(() => ({ theme: "dark"}), []);Senior-Level Interview Questions
Section titled “Senior-Level Interview Questions”Why can excessive useMemo hurt performance?
Section titled “Why can excessive useMemo hurt performance?”Every memoized value:
- Consumes memory
- Requires dependency comparison
- Adds maintenance overhead
For inexpensive calculations, the overhead may exceed the benefit.
useMemo with React.memo
Section titled “useMemo with React.memo”Parent:
const user = useMemo(() => ({ id: 1, name: "John"}), []);
return <Child user={user} />;Child:
const Child = React.memo(({ user }) => { console.log("Rendered"); return <div>{user.name}</div>;});Without useMemo, a new object reference causes unnecessary child re-renders.
Object Dependency Problem
Section titled “Object Dependency Problem”const filter = { active: true};
useMemo(() => { return users.filter(...);}, [filter]);Fix:
const filter = useMemo(() => ({ active: true}), []);Performance Optimization Strategy
Section titled “Performance Optimization Strategy”React.memo-> Avoid unnecessary component re-rendersuseCallback-> Stable function referencesuseMemo-> Stable computed values- Virtualization -> Efficient rendering of large lists
- Code splitting -> Smaller bundles
Real-world Use Cases
Section titled “Real-world Use Cases”- Data grid filtering
- Search results
- Pagination calculations
- Dashboard analytics
- Chart data transformations
- Sorting large datasets
- Tree structure generation
- Permission calculations
Tricky Interview Question
Section titled “Tricky Interview Question”Q: Does React guarantee that useMemo will always return the cached value?
Answer: No.
useMemo is a performance optimization hint, not a semantic guarantee. React may discard cached values during certain optimizations and recompute them. Your application should remain correct even if recomputation occurs.
One-Line Interview Answer
Section titled “One-Line Interview Answer”“
useMemocaches the result of an expensive computation and recomputes it only when its dependencies change, improving rendering performance by avoiding unnecessary calculations.”
Summary
Section titled “Summary”- Use
useMemoto cache expensive synchronous computations. - Avoid using it for cheap calculations or API calls.
- It memoizes values, not components or functions.
- Combine it with
React.memoanduseCallbackfor broader performance optimizations. - Treat
useMemoas an optimization, not a correctness guarantee.