π React useMemo β Complete In-Depth Guide
1. Introduction
πΉ What is useMemo?
useMemo is a React Hook used to memoize (cache) the result of a computation so that it is only recalculated when its dependencies change.
πΉ Why is it important in React?
React re-renders components frequently. During each render:- All functions inside the component run again
- Expensive computations can degrade performance
useMemo helps:
- Avoid recomputing expensive calculations
- Reduce CPU usage
- Improve render performance
- Stabilize derived values for referential equality
πΉ When and why we use it
UseuseMemo when:
β Expensive Computations
β Preventing Unnecessary Re-renders (Referential Equality)
β Stable Props for Child Components
2. Concepts / Internal Workings
πΉ Core Concept: Memoization
Memoization means:Cache the result of a function and reuse it unless inputs change.
πΉ How useMemo Works Internally
At a high level:
-
React stores:
- Last computed value
- Dependency array
-
On re-render:
- React compares dependencies (shallow comparison)
- If unchanged β return cached value
- If changed β recompute
πΉ Dependency Array Behavior
- Compared using Object.is
- Works well for primitives
- Objects/arrays need stable references
πΉ Relationship with React Rendering
useMemoruns during render phase- It is not async
- It does not prevent re-renders, only computation
πΉ Relationship with Other Hooks
useCallback
useMemoβ memoizes valueuseCallbackβ memoizes function
useEffect
React.memo
useMemohelps create stable propsReact.memouses them to avoid re-render
πΉ Referential Equality
Important concept:useMemo:
useMemo:
3. Syntax & Examples
πΉ Basic Syntax
πΉ Example 1: Expensive Calculation
πΉ Example 2: Filtering List
πΉ Example 3: Sorting Data
πΉ Example 4: Stable Object for Child
πΉ Example 5: Avoiding Recalculation in Parent Re-render
πΉ Mini Example Variations
Without useMemo
With useMemo
Memoizing Array
Memoizing Derived Value
4. Edge Cases / Common Mistakes
β Overusing useMemo
β Missing Dependencies
β Using for Side Effects
useEffect instead.
β Memoizing Mutable Data
β Wrong Expectation: Prevent Re-render
β Dependency on Non-stable Objects
data changes reference every render β memo breaks.
β Expensive Comparison vs Computation
Sometimes:- Dependency comparison cost > computation cost
useMemo useless or worse.
5. Best Practices
β Use Only When Needed
Ask:- Is computation expensive?
- Is re-render frequent?
β Prefer Simplicity First
β Stabilize Props for Memoized Components
β Keep Dependency Arrays Correct
Use ESLint rule:β
Avoid Nested useMemo Complexity
Bad:
β Measure Before Optimizing
Use:- React DevTools Profiler
- Performance tab
β Use for Referential Stability (Important)
Especially for:- Props to memoized children
- Dependency arrays in other hooks
β
Combine with React.memo
β Avoid Heavy Logic Inside JSX
π Final Mental Model
-
useMemois a performance optimization tool, not a default tool -
It trades:
- Memory + complexity for CPU savings
-
Use it when:
- Computation is expensive
- Referential stability matters
-
Avoid when:
- Logic is simple
- Premature optimization
Below is a senior-level, depth-focused set of conceptual questions on
useMemo.
Each question is designed to test how you think, not just what you know.
π§ Advanced useMemo Interview Questions (Senior Level)
1. What problem does useMemo actually solve in Reactβs rendering model?
β Answer
useMemo solves unnecessary recomputation, not re-rendering.
Reactβs rendering model:
- Every render β component function runs again
- All calculations inside are re-executed
data didnβt change.
Solution:
π WHY
- React has no built-in memoization for computations
useMemointroduces manual caching- It optimizes CPU work, not reconciliation
βοΈ Alternative
- Move computation outside component β not possible if it depends on props/state
- Use Web Workers β for heavy async work
2. How does useMemo work internally in React?
β Answer
Internally, React:-
Stores:
- Last computed value
- Dependency array
-
On next render:
- Compares dependencies using Object.is
- If same β returns cached value
- If different β recomputes
π WHY
React uses a hook state list per fiber node:- Each
useMemooccupies a slot - Dependencies stored alongside value
β οΈ Important Insight
- Comparison is shallow
- No deep equality check
3. Why is useMemo not guaranteed to always memoize?
β Answer
Because React treats it as a performance hint, not a strict guarantee. React may:- Drop memoized values (e.g., memory pressure, concurrent mode)
- Recompute anyway
π WHY
React prioritizes:- Correctness
- Simplicity of implementation
- Memory efficiency
π« Implication
Never rely onuseMemo for correctness:
4. How does useMemo behave in React Strict Mode?
β Answer
In Strict Mode (development only):- The function inside
useMemomay run twice
π WHY
Strict Mode intentionally:- Detects side effects
- Forces double execution
β οΈ Implication
useMemomust be pure- No side effects allowed
5. When does useMemo actually hurt performance?
β Answer
When:1. Computation is cheap
2. Dependencies change frequently
3. Memory overhead > CPU savings
π WHY
useMemo adds:
- Memory usage
- Dependency comparison cost
- Code complexity
βοΈ Trade-off
6. Explain referential equality and why useMemo is critical for it.
β Answer
Referential equality:- Causes unnecessary child re-renders
π WHY
React compares props by reference, not deep equality.βοΈ Alternative
React.memoβ skips render if props unchanged- But needs stable references β
useMemohelps
7. Why is useMemo often paired with React.memo?
β Answer
Because they solve different parts of the problem:useMemoβ stabilizes valuesReact.memoβ skips re-render
π WHY
WithoutuseMemo:
- New reference each render β
React.memouseless
8. What happens if you omit dependencies in useMemo?
β Answer
You get stale values.π WHY
- React doesnβt track variables inside function
- It relies entirely on dependency array
β οΈ Result
- Bugs that are hard to detect
- Inconsistent UI
9. Why is using objects/arrays as dependencies tricky?
β Answer
Because of reference instability:π WHY
- New object created every render
- Reference changes β memo invalidated
β Fix
10. Can useMemo replace useEffect?
β Answer
No.π WHY
π« Wrong usage
11. How does useMemo interact with closures?
β Answer
It captures values from the render it was created in.π Problem
countis stale if not in dependencies
β Fix
12. Whatβs the difference between memoizing a value vs computing inline?
β Answer
Inline:π WHY it matters
- Inline β recompute every render
- Memo β reuse cached result
βοΈ Decision
Use memo only when:- Computation is expensive
- Renders are frequent
13. Why shouldnβt you mutate values returned from useMemo?
β Answer
Because it breaks predictability.π WHY
- React assumes immutability
- Mutation causes hidden bugs
14. How does useMemo behave with asynchronous logic?
β Answer
It doesnβt handle async well.π Problem
- Returns a Promise
- Not reactive
β Correct approach
UseuseEffect + state
15. What is the difference between useMemo and caching outside React?
β Answer
External caching:π Difference
16. How does useMemo behave in concurrent rendering?
β Answer
- React may start rendering, pause, discard work
useMemomay recompute multiple times
π WHY
Concurrent mode:- Prioritizes responsiveness
- Work can be interrupted
β οΈ Implication
- Computation must be pure and cheap enough
17. Why is useMemo not a substitute for proper data structures?
β Answer
Bad:π WHY
- Algorithmic improvement > memoization
O(n)vsO(1)
18. When would you remove useMemo from a codebase?
β Answer
When:- No measurable performance gain
- Dependencies change frequently
- Code becomes harder to read
π WHY
Premature optimization:- Adds complexity
- No real benefit
19. How do you decide if useMemo is needed?
β Answer
Ask:- Is computation expensive?
- Does it run frequently?
- Are dependencies stable?
π Tools
- React DevTools Profiler
- Performance profiling
20. Explain a real-world scenario where useMemo is critical.
β Answer
Scenario: Large data table
π WHY
- Filtering large datasets is expensive
- Prevents recomputation on unrelated renders
βοΈ Without useMemo
- UI becomes slow
- CPU spikes
π Final Insight
A senior engineer understands:
useMemo is not about βoptimizing everythingβ β
itβs about controlling when work happens in React.
Below are senior-level, tricky MCQs on
useMemo designed to test deep understanding, not recall.
π§ Advanced MCQs on useMemo
1. What will happen when this component re-renders?
Options:
A. Logs on every render B. Logs only on first render C. Logs only whencount changes
D. Logs twice on every render
β Correct Answer: B
Explanation:
- Dependency array is
[]β runs only once countis ignored β stale value
Why others are wrong:
- A: Incorrect β dependencies prevent rerun
- C: Incorrect β
countnot included - D: Incorrect β Strict Mode only doubles in dev, not always
2. What is the real issue in this code?
Options:
A. Causes unnecessary re-renders B. Adds unnecessary overhead C. Causes stale closure D. Breaks referential equalityβ Correct Answer: B
Explanation:
a + bis trivial β memoization cost > benefit
Why others are wrong:
- A:
useMemodoesnβt trigger re-renders - C: Dependencies are correct β no stale closure
- D: Not relevant for primitives
3. What happens if dependencies change every render?
Options:
A.useMemo caches result correctly
B. useMemo recomputes every render
C. React throws an error
D. Value becomes stale
β Correct Answer: B
Explanation:
- New object β new reference β dependency changes β recompute
Why others are wrong:
- A: False β reference instability
- C: No runtime error
- D: Opposite β always fresh
4. Why is this problematic?
Options:
A.fetchData runs twice
B. Side effects in render phase
C. Dependency issue
D. Memory leak
β Correct Answer: B
Explanation:
useMemoruns during render β side effects are unsafe
Why others are wrong:
- A: Only in Strict Mode (dev), not core issue
- C: Dependencies are fine
- D: Not necessarily
5. Which scenario justifies useMemo the most?
A. const total = a + b
B. const list = items.map(x => x * 2) (small array)
C. Filtering a 10k item dataset
D. Rendering JSX
β Correct Answer: C
Explanation:
- Expensive computation + frequent renders
Why others are wrong:
- A: trivial
- B: small computation
- D: irrelevant
6. What is true about useMemo and re-renders?
A. It prevents component re-render
B. It prevents child re-render
C. It only memoizes computation
D. It stops React reconciliation
β Correct Answer: C
Explanation:
- It only caches value, not render cycle
Why others are wrong:
- A/B: Needs
React.memo - D: Incorrect understanding
7. What will happen here?
Options:
A. Safe and expected B. Causes re-render C. Breaks immutability assumptions D. React throws errorβ Correct Answer: C
Explanation:
- Mutation breaks predictable behavior
Why others are wrong:
- A: Not safe
- B: No re-render triggered
- D: React doesnβt detect mutation
8. Why might this still re-render child?
Options:
A.useMemo doesnβt work with objects
B. Child is not memoized
C. Dependency array is wrong
D. React ignores memo
β Correct Answer: B
Explanation:
- Child re-renders unless wrapped in
React.memo
9. Whatβs the subtle bug here?
Options:
A. Performance issue B. Stale value C. Infinite loop D. Syntax errorβ Correct Answer: B
Explanation:
countnot in dependencies β stale
10. What is the main cost of useMemo?
A. CPU
B. Memory + comparison overhead
C. Network
D. DOM updates
β Correct Answer: B
Explanation:
- Stores cached value + compares dependencies
11. How is useMemo different from useCallback?
A. No difference
B. useMemo returns function
C. useCallback is syntactic sugar over useMemo
D. useMemo is async
β Correct Answer: C
Explanation:
12. What happens in Strict Mode?
Options:
A.useMemo runs once
B. Runs twice in dev
C. Skipped entirely
D. Throws warning
β Correct Answer: B
Explanation:
- Double invocation to detect side effects
13. Why is this inefficient?
Options:
A. Sorting is cheap B. Mutates original array C. Dependency issue D. Memoization failsβ Correct Answer: B
Explanation:
.sort()mutates β side effects
14. Which is better?
A.β Correct Answer: B
Explanation:
- Algorithm improvement > memoization
15. When can React ignore useMemo cache?
Options:
A. Never B. In concurrent rendering C. Only in production D. Only with objectsβ Correct Answer: B
Explanation:
- React may discard work in concurrent mode
16. Whatβs wrong with this pattern?
Options:
A. Syntax error B. Missing dependency C. Performance issue D. Infinite loopβ Correct Answer: B
Explanation:
thememissing β stale config
17. Why is this not useful?
Options:
A. Boolean not supported B. No computation to optimize C. Causes re-render D. Dependency issueβ Correct Answer: B
18. What happens here?
Options:
A. Runs once B. Never runs C. Runs every render D. Throws errorβ Correct Answer: C
Explanation:
Math.random()changes β dependency always different
π Final Insight
A strong engineer understands:useMemois not a default tool- Itβs a trade-off mechanism
- The real skill is knowing when NOT to use it
Below are 18 high-quality coding problems on
useMemo, designed to simulate real-world engineering scenarios.
Each focuses on performance, correctness, and decision-making.
π§ useMemo Coding Problems (Senior Level)
1. Optimizing Large List Filtering
π§© Problem
You have a list of 50,000 users. Implement search filtering without degrading performance.Constraints
- Frequent re-renders (typing input)
- Dataset is large
Expected Behavior
- Filtering runs only when
queryoruserschanges
Edge Cases
- Empty query β return full list
- Case-insensitive search
β Solution
π Explanation
- Prevents expensive filtering on unrelated renders
2. Preventing Expensive Sorting on Every Render
π§© Problem
Sort products by price efficiently.Constraints
- Products array may update occasionally
- Sorting is expensive
Edge Cases
- Stable sorting
- Avoid mutating original array
β Solution
π Explanation
- Avoids mutation + avoids repeated sort
3. Stabilizing Props for Memoized Child
π§© Problem
A child wrapped inReact.memo still re-renders.
Expected Behavior
- Child should not re-render unnecessarily
β Solution
π Explanation
- Prevents new object reference
4. Derived State from Complex Computation
π§© Problem
Calculate total cart price with discounts.Constraints
- Cart updates occasionally
- Discounts logic complex
β Solution
5. Avoid Recomputing Heavy Math
π§© Problem
Compute factorial for large number.Edge Cases
- n = 0
- large n (performance)
β Solution
6. Memoizing Expensive Chart Data Transformation
π§© Problem
Transform API data for chart rendering.Constraints
- Data transformation expensive
- Chart re-renders often
β Solution
7. Prevent Infinite Loop in useEffect Dependency
π§© Problem
Effect depends on object β infinite loopβ Fix
π Explanation
- Stabilizes dependency
8. Optimizing Table Column Definitions
π§© Problem
Columns re-created β table re-rendersβ Solution
9. Avoid Expensive Regex Execution
π§© Problem
Heavy regex validation runs on every renderβ Solution
10. Dynamic Theme Computation
π§© Problem
Theme object depends on user settingsβ Solution
11. Debounced Search Optimization (Combined Thinking)
π§© Problem
Search input triggers expensive filteringConstraint
- Avoid recompute on every keystroke instantly
β Solution
12. Memoizing Context Value
π§© Problem
Context provider causes re-rendersβ Solution
13. Preventing Recalculation in Parent Re-renders
π§© Problem
Parent re-renders β heavy computation rerunsβ Solution
14. Avoid Recomputing Derived Map
π§© Problem
Convert array to lookup mapβ Solution
15. Optimizing Permission Checks
π§© Problem
Complex permission logic runs repeatedlyβ Solution
16. Memoizing Computed Styles
π§© Problem
Inline styles cause child re-renderβ Solution
17. Avoiding Re-render in Virtualized List
π§© Problem
Visible rows computation is expensiveβ Solution
18. Expensive Data Grouping
π§© Problem
Group orders by categoryβ Solution
π Final Takeaways
These problems test whether you:- Recognize when computation is expensive
- Understand referential equality
- Avoid premature optimization
- Use
useMemofor real performance wins
Below are 18 real-world debugging challenges involving
useMemo, written the way they typically show up in production code reviews.
Each one tests your ability to spot subtle bugs, incorrect assumptions, and performance traps.
π§ useMemo Debugging Challenges (Senior Level)
1. Stale Value Bug
β Whatβs wrong?
- Missing dependencies β stale value
π€ WHY it happens
useMemoonly runs once β ignores updates topriceorquantity
β Fix
π‘ Best Practice
- Always include all reactive values in dependencies
2. Memoization Broken by Reference
β Whatβs wrong?
filtersrecreated every render β memo useless
π€ WHY
- New object reference each render
β Fix
π‘ Best Practice
- Stabilize objects used as dependencies
3. Side Effect Inside useMemo
β Whatβs wrong?
- Side effects inside render phase
π€ WHY
useMemoruns during render β unsafe
β Fix
π‘ Best Practice
useMemo= pure computation only
4. Mutating Memoized Value
β Whatβs wrong?
- Mutating memoized object
π€ WHY
- Breaks immutability β unpredictable UI
β Fix
π‘ Best Practice
- Never mutate memoized values
5. Overusing useMemo
β Whatβs wrong?
- Unnecessary optimization
π€ WHY
- Computation is trivial β overhead > benefit
β Fix
π‘ Best Practice
- Optimize only when measurable
6. Sorting Mutation Bug
β Whatβs wrong?
.sort()mutates original array
π€ WHY
- Causes hidden state bugs
β Fix
π‘ Best Practice
- Always avoid mutating inputs
7. Incorrect Dependency
β Whatβs wrong?
- Missing
bdependency
π€ WHY
- Leads to stale computation
β Fix
8. Infinite Loop via useEffect + useMemo
β Whatβs wrong?
configchanges every render β effect loops
π€ WHY
- New object reference
β Fix
9. Misunderstanding: Preventing Re-render
β Whatβs wrong?
- Does nothing useful
π€ WHY
- Component still re-renders
β Fix
- Remove it
π‘ Best Practice
useMemoβ render optimization
10. Async useMemo Bug
β Whatβs wrong?
- Returns a Promise, not data
π€ WHY
useMemonot designed for async
β Fix
11. Hidden Dependency via Closure
β Whatβs wrong?
multipliermissing
π€ WHY
- Closure captures old value
β Fix
12. Expensive Dependency Comparison
β Whatβs wrong?
- Expensive stringification each render
π€ WHY
- Worse than recomputation
β Fix
- Stabilize
dataupstream
13. useMemo Inside Loop (Invalid Pattern)
β Whatβs wrong?
- Hooks inside loop β violates rules
π€ WHY
- Hook order must be consistent
β Fix
- Move logic outside loop or inside child
14. Misplaced Optimization
β Whatβs wrong?
- Hook inside JSX
π€ WHY
- Violates hook rules
β Fix
15. Dependency on Function Without Memoization
β Whatβs wrong?
fnchanges every render
π€ WHY
- Functions are new references
β Fix
16. Misusing useMemo for Constant
β Whatβs wrong?
- Useless memoization
π€ WHY
- Constant doesnβt need memoization
β Fix
17. Incorrect Assumption About Cache Persistence
β Whatβs wrong?
- Assuming it will NEVER recompute
π€ WHY
- React may discard cache (concurrent mode)
β Fix
- Ensure computation is safe to rerun
18. Derived State Anti-pattern
β Whatβs wrong?
- Derived state stored unnecessarily
π€ WHY
- Causes extra render
β Fix
π Final Insight
These bugs reveal whether someone truly understands:- Reactβs render model
- Referential equality
- Hook lifecycle constraints
- Performance trade-offs
Below are 18 production-grade machine coding problems focused on
useMemo, designed at the level expected in top tech interviews and real-world systems.
Each problem forces you to think about render cost, memoization strategy, and data flow architecture β not just UI.
π§ Real-World Machine Coding Problems (useMemo Focus)
1. Scalable Data Table with Multi-Level Filtering & Sorting
π§© Requirements
- Render 10k+ rows
-
Support:
- Global search
- Column filters
- Multi-column sorting
π₯οΈ UI Behavior
- Instant feedback on filter change
- Sorting toggles (asc/desc)
π Data Flow
data β filtered β sorted β paginated
β οΈ Edge Cases
- Empty filters
- Multiple filters applied
- Sorting on missing fields
β‘ Performance
- Avoid recomputing pipeline on unrelated renders
ποΈ Architecture
- Separate transformation steps
- Memoize each stage
β Approach
2. Real-Time Search with Debounce + Highlighting
π§© Requirements
- Search large text dataset
- Highlight matches
π₯οΈ UI Behavior
- Debounced typing (300ms)
- Highlight matched substrings
β οΈ Edge Cases
- Special characters in search
- Empty query
β‘ Performance
- Avoid recomputing highlight logic unnecessarily
ποΈ Architecture
debouncedQuerystate- Memoize filtered + highlighted result
β Approach
3. Virtualized Infinite Scroll Feed
π§© Requirements
- Load items progressively
- Only render visible items
π₯οΈ UI Behavior
- Smooth scrolling
- Dynamic loading
β οΈ Edge Cases
- Fast scrolling
- Empty feed
β‘ Performance
- Slice visible items efficiently
ποΈ Architecture
visibleRangestate
β Approach
4. Complex Pricing Engine (E-commerce)
π§© Requirements
-
Compute final price:
- Discounts
- Coupons
- Taxes
β οΈ Edge Cases
- Invalid coupons
- Stackable discounts
β‘ Performance
- Avoid recomputation on UI-only updates
ποΈ Architecture
- Derived pricing state via memo
β Approach
5. Role-Based Permission Matrix
π§© Requirements
- Show permissions grid (users Γ actions)
π₯οΈ UI Behavior
- Toggle permissions
β οΈ Edge Cases
- Inherited roles
- Conflicting permissions
β‘ Performance
- Avoid recomputing matrix for each render
ποΈ Architecture
- Precompute lookup maps
β Approach
6. Analytics Dashboard with Heavy Aggregations
π§© Requirements
- Display charts from large dataset
-
Aggregate:
- daily
- weekly
- monthly
β‘ Performance
- Aggregation is CPU heavy
ποΈ Architecture
- Memoize transformed dataset
β Approach
7. Dynamic Form Builder
π§© Requirements
- Render forms from schema
- Support conditional fields
β οΈ Edge Cases
- Field dependencies
- Dynamic validation
β‘ Performance
- Avoid recomputing schema
ποΈ Architecture
- Memoize derived form structure
8. Multi-Select Dropdown with Search + Grouping
π§© Requirements
- Grouped options
- Search filter
β‘ Performance
- Large option set (5k+)
ποΈ Architecture
- Memoize grouped + filtered options
9. Code Editor with Syntax Highlighting
π§© Requirements
- Highlight code dynamically
β‘ Performance
- Regex parsing is expensive
ποΈ Architecture
- Memoize tokenized output
10. Image Gallery with Dynamic Layout
π§© Requirements
- Masonry layout
- Responsive resizing
β‘ Performance
- Layout calculation expensive
ποΈ Architecture
11. Financial Portfolio Tracker
π§© Requirements
-
Calculate:
- Gains/losses
- Percent change
β οΈ Edge Cases
- Missing prices
- Real-time updates
β‘ Performance
- Avoid recomputation on UI-only changes
12. Chat App Message Grouping
π§© Requirements
- Group messages by date/user
β‘ Performance
- Large message list
13. Advanced Calendar Scheduler
π§© Requirements
- Compute overlapping events
- Render time slots
β‘ Performance
- Complex time calculations
14. Graph Editor (Nodes & Edges)
π§© Requirements
- Render graph connections
β‘ Performance
- Layout calculation expensive
15. Smart Recommendation Engine (Frontend)
π§© Requirements
- Recommend items based on behavior
β‘ Performance
- Scoring algorithm expensive
16. JSON Viewer with Expand/Collapse
π§© Requirements
- Render deeply nested JSON
β‘ Performance
- Parsing expensive
17. Drag-and-Drop Kanban Board
π§© Requirements
- Reorder tasks
- Group by columns
β‘ Performance
- Avoid recomputing layout
18. AI Prompt Builder UI
π§© Requirements
- Build prompt dynamically from inputs
β οΈ Edge Cases
- Missing variables
- Formatting rules
β‘ Performance
- String building complex
π Final Architectural Insight
A senior engineer should recognize:π useMemo is critical when:
- You have multi-stage transformations
- Data size is large
- Computation is non-trivial
- Referential stability affects child components
β οΈ But:
- It should be applied surgically, not everywhere
-
Often combined with:
React.memouseCallback- Proper data structures
Below are FAANG-level interview questions on
useMemo, designed to test deep reasoning, trade-offs, and real-world decision-making.
π§ Advanced useMemo Interview Questions (Senior Level)
1. When would you deliberately NOT use useMemo, even if a computation is expensive?
π Follow-up
- What if the component renders infrequently?
- What if dependencies change often?
β Strong Answer
- If renders are rare β memoization overhead not justified
- If dependencies change frequently β cache invalidates anyway
- If memory overhead outweighs CPU savings
- Prefer algorithmic optimization first
β Weak Answer
- βAlways use it for expensive computationsβ
2. How would you debug a case where useMemo is not improving performance?
π Follow-up
- What tools would you use?
- What metrics matter?
β Strong Answer
- Use React DevTools Profiler
-
Check:
- Recompute frequency
- Dependency changes
-
Validate:
- Is computation actually expensive?
- Are dependencies stable?
β Weak Answer
- βAdd more
useMemoβ
3. Explain a situation where useMemo introduces a bug instead of fixing performance.
π Follow-up
- How would you detect it?
β Strong Answer
- Missing dependency β stale data
- Example:
- Leads to inconsistent UI
β Weak Answer
- βIt can cause performance issuesβ
4. How does referential equality impact component re-renders, and how does useMemo help?
π Follow-up
- Why is this critical for
React.memo?
β Strong Answer
- React compares props by reference
- New object each render β triggers child re-render
useMemostabilizes reference
β Weak Answer
- βIt caches valuesβ
5. How would you design a data transformation pipeline using useMemo?
π Follow-up
- Where would you split memoization?
β Strong Answer
- Break into stages:
- Memoize each step independently
- Minimizes recomputation
β Weak Answer
- βWrap everything in one
useMemoβ
6. What are the trade-offs of using useMemo in a large-scale app?
π Follow-up
- Memory vs CPU trade-off?
β Strong Answer
-
Pros:
- Reduced computation
-
Cons:
- Memory usage
- Dependency tracking complexity
- Debugging difficulty
β Weak Answer
- βIt improves performanceβ
7. Why is useMemo not a guarantee of memoization?
π Follow-up
- How does concurrent rendering affect this?
β Strong Answer
- React may discard cached values
- Concurrent mode can re-run computations
- Itβs an optimization hint, not a contract
β Weak Answer
- βBecause dependencies changeβ
8. How would you handle expensive computations that depend on unstable objects?
π Follow-up
- Where would you fix instability?
β Strong Answer
- Stabilize upstream:
- Or normalize data structure
β Weak Answer
- βJust add it to dependenciesβ
9. Compare useMemo vs moving computation outside the component.
π Follow-up
- When is each appropriate?
β Strong Answer
-
Outside component:
- Static logic
-
useMemo:- Depends on props/state
- Needs reactivity
β Weak Answer
- βThey are the sameβ
10. How would you detect overuse of useMemo in a codebase?
π Follow-up
- What signals indicate misuse?
β Strong Answer
- Memoizing trivial values
- Complex dependency arrays
- No measurable performance gain
β Weak Answer
- βToo many hooksβ
11. Why is useMemo not suitable for async operations?
π Follow-up
- Whatβs the correct pattern?
β Strong Answer
- Runs during render β must be synchronous
- Async returns Promise β breaks flow
- Use
useEffect+ state
β Weak Answer
- βIt doesnβt support asyncβ
12. How does useMemo interact with closures?
π Follow-up
- What happens if dependency is missing?
β Strong Answer
- Captures values at render time
- Missing dependency β stale closure
β Weak Answer
- βIt remembers valuesβ
13. When would you prefer algorithmic optimization over useMemo?
π Follow-up
- Give an example
β Strong Answer
- Example:
- Algorithm > memoization
β Weak Answer
- βWhen performance is badβ
14. How would you optimize a component re-rendering due to inline objects?
π Follow-up
- What if object depends on props?
β Strong Answer
- Stabilizes reference
β Weak Answer
- βMove it outsideβ
15. Explain a real-world case where useMemo is critical.
π Follow-up
- What happens without it?
β Strong Answer
- Large dataset filtering
-
Without memo:
- CPU spikes
- UI lag
β Weak Answer
- βFor performanceβ
16. How would you refactor a component misusing useMemo everywhere?
π Follow-up
- Whatβs your strategy?
β Strong Answer
- Remove unnecessary memoization
- Profile first
- Keep only high-impact cases
β Weak Answer
- βDelete all of themβ
17. Can useMemo cause memory leaks?
π Follow-up
- In what scenarios?
β Strong Answer
-
Not directly, but:
- Large cached objects retained
- Long-lived components β memory growth
β Weak Answer
- βNoβ
18. How would you ensure correctness when using useMemo?
π Follow-up
- Tooling?
β Strong Answer
- Use ESLint rules (
exhaustive-deps) - Ensure pure functions
- Avoid side effects
β Weak Answer
- βTest it manuallyβ
19. Whatβs your mental model for deciding useMemo usage?
π Follow-up
- What signals trigger it?
β Strong Answer
-
Ask:
- Is computation expensive?
- Is it repeated?
- Are dependencies stable?
β Weak Answer
- βUse it when neededβ
20. How does useMemo fit into overall React performance strategy?
π Follow-up
- What comes before it?
β Strong Answer
-
Order:
- Fix unnecessary re-renders
- Optimize algorithms
- Use
useMemoas last step
β Weak Answer
- βIt improves performanceβ
π Final Insight
A FAANG-level engineer doesnβt just knowuseMemo β they know:
- When it adds value
- When it adds complexity
- How it fits into holistic performance strategy