What is the difference between useMemo and useCallback?

💡 Concept Name

useMemo vs useCallback – Both are React hooks used to optimize performance by memoizing values or functions. useMemo returns a memoized value, while useCallback returns a memoized function.

📘 Quick Intro

React’s useMemo caches the result of a computation, and useCallback caches a function reference. Both help avoid unnecessary recomputations or re-renders, especially in complex component trees.

🧠 Analogy / Short Story

Imagine you’re doing math homework. If you calculate 7 × 8 once and write down the answer (56), that’s useMemo — caching the result.

If you write down how you calculated it (“multiply 7 and 8”) as a method to reuse later, that’s useCallback — caching the function.

🔧 Technical Explanation

  • useMemo(() => computeFn(), [deps]) memoizes the value of computeFn.
  • useCallback(() => handlerFn, [deps]) memoizes the function reference.
  • useMemo is ideal for expensive calculations you don’t want to repeat unless dependencies change.
  • useCallback is best for passing stable functions to child components to avoid unnecessary renders.
  • Both improve performance but should be used thoughtfully to avoid memory overhead.

💻 Real Code Example


import React, { useState, useMemo, useCallback } from 'react';

const ExpensiveList = React.memo(({ onClick }) => {
  console.log('Child re-rendered');
  return <button onClick={onClick}>Click Me</button>;
});

export default function App() {
  const [count, setCount] = useState(0);

  const expensiveValue = useMemo(() => {
    console.log('Calculating...');
    return count * 2;
  }, [count]);

  const handleClick = useCallback(() => {
    console.log('Button clicked');
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <p>Expensive Value: {expensiveValue}</p>
      <ExpensiveList onClick={handleClick} />
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
    

❓ Interview Q&A

Q1: What is the purpose of useMemo?
A: To memoize the result of an expensive computation to avoid recalculating it on every render.

Q2: When should you use useCallback?
A: When you want to avoid recreating the same function on every render, especially when passing callbacks to child components.

Q3: What does useCallback return?
A: It returns a memoized version of a callback function that only changes if dependencies change.

Q4: Can useMemo return a function?
A: Yes, but it’s better to use useCallback when your goal is to memoize a function.

Q5: How do useMemo and useCallback improve performance?
A: By preventing unnecessary re-renders or recalculations when props or state haven’t changed.

Q6: Is useCallback just syntactic sugar for useMemo?
A: Kind of — useCallback(fn, deps) is equivalent to useMemo(() => fn, deps), but it's semantically clearer.

Q7: What is the dependency array in both hooks used for?
A: It tells React when to recompute the memoized value or function.

Q8: Can you overuse useMemo/useCallback?
A: Yes, unnecessary usage can increase memory and code complexity without benefits.

Q9: What hook is preferred for memoizing a component’s callback function?
A: useCallback

Q10: Can useMemo replace useCallback in all cases?
A: Technically yes, but semantically it’s better to use the appropriate hook for clarity and intent.

📝 MCQs

Q1. What does useMemo return?

  • A memoized value
  • A memoized function
  • Nothing
  • A component

Q2. What is the purpose of useCallback?

  • Execute code on mount
  • Memoize a value
  • Track dependencies
  • Memoize function reference

Q3. Which hook helps prevent unnecessary re-renders in child components due to new function props?

  • useMemo
  • useEffect
  • useCallback
  • useRef

Q4. Which hook is best for expensive calculations?

  • useCallback
  • useReducer
  • useMemo
  • useLayoutEffect

Q5. What does useCallback depend on to re-generate the function?

  • setState
  • Refs
  • Context
  • Dependency array

Q6. Can useMemo return a function?

  • No
  • Yes
  • Only in class components
  • Only inside useEffect

Q7. Which hook is syntactic sugar over the other?

  • useMemo over useCallback
  • useEffect over useRef
  • useCallback over useMemo
  • useRef over useMemo

Q8. What type does useCallback return?

  • Number
  • Array
  • Component
  • Function

Q9. What is the goal of useMemo?

  • Avoid prop drilling
  • Fetch data
  • Avoid recalculating a value unnecessarily
  • Create portals

Q10. When do useMemo and useCallback re-compute their result?

  • On every render
  • Only once
  • When dependencies change
  • When event fires

💡 Bonus Insight

To debug memoization, use the React DevTools Profiler and console logs to ensure your hooks are truly preventing re-renders or re-computations. Don’t optimize prematurely — profile first!

📄 PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

💬 Feedback
🚀 Start Learning
Share:

Tags: