useMemo Hook in React js and usememo vs usecallback

useMemo

useMemo

Table of Contents

     

    What is Memoization?

     

    Background

    The term “Memoization” came from the Latin word “memorandum” (to remember), which is shortened to “memo” in American English which means “to transform the results of a function into something to remember.”.

     

    Memoization

    In computing term, memoization is refered to speed up computer programs by eliminating the repetitive computation of results, and by avoiding repeated method calls that process the same input.

     

    useMemo

    In the context of programming, particularly in React.js, `useMemo` is a hook used for memoizing expensive computations so that they are only re-executed when one of the dependencies has changed.

    In React, when a component re-renders, all of its code is executed again, including any expensive computations. This can be inefficient if those computations don’t need to be recalculated on every render.

    `useMemo` allows you to optimize performance by memoizing the result of a function or computation and only recalculating it when the inputs to that function change. It takes two arguments: the first is a function that performs the computation, and the second is an array of dependencies. The result of the computation is memoized and will only be recalculated when one of the dependencies changes.

    Here’s a basic example:

    import React, { useMemo } from ‘react’;

    const MyComponent = ({ a, b }) => {
    const result = useMemo(() => {
    // Expensive computation
    return a * b;
    }, [a, b]); // Recalculate result only if ‘a’ or ‘b’ changes

    return <div>{result}</div>;
    };

    export default MyComponent;

    In this example, the multiplication of `a` and `b` is an expensive computation. By using `useMemo`, we ensure that the multiplication is only performed again if either `a` or `b` changes. This can lead to significant performance improvements in components with complex computations.

    React’s functional component uses the useMemo hook, which yields a memoized value.

    Syntex

    useMemo() is a built-in React hook that accepts two arguments — a function compute that computes a result, and the depedencies array

     

    react.memo

    react.memo is used in higher-order component that is used to memoize a component, which means it caches the output of the component and only re-renders it if its props have changed. This can be useful when a component’s rendering is expensive, and you want to avoid unnecessary re-renders. Memo can be imported from ‘react’ and wrapped around a functional component.

    useMemo vs useCallback

    The useMemo and useCallback Hooks are similar. The main difference is that useMemo returns a memoized value and useCallback returns a memoized function

     

    What problem solved in useMemo ?

    Improve Application Performance

     

    How to implement Memoization concept in class component ?

    Using PureComponent

     

    Does useMemo have any disadvantage?

    Yes we can’t call useMemo in loop like

    Resolution

     

    YouTube Video


    Top 10 useMemo Interview Questions and Answers

    1. What is useMemo in React?

    useMemo is a React Hook that memoizes the result of a function, ensuring that it only recomputes when dependencies change. This helps optimize performance by preventing unnecessary calculations.

    Example:

    import { useMemo, useState } from "react";
    
    function ExpensiveCalculation({ num }) {
      const squared = useMemo(() => {
        console.log("Computing...");
        return num * num;
      }, [num]);
    
      return <p>Squared Value: {squared}</p>;
    }
    

    Key Benefit: Avoids recalculating num * num unless num changes.

    2. When should you use useMemo?

    Use useMemo in the following scenarios:
    Expensive Computations: If a function performs complex calculations.
    Referential Equality Issues: To prevent unnecessary renders in child components.
    Avoiding Recalculations in Rendering: When data transformation is computationally heavy.

    🔴 Avoid useMemo when:
    ❌ The computation is fast.
    ❌ You don’t have performance issues.

    3. What happens if we use useMemo incorrectly?

    If useMemo is misused:

    • Memory Overhead: Storing unnecessary cached values.
    • Unnecessary Complexity: Using useMemo for simple calculations.
    • No Performance Improvement: If dependencies change frequently, recomputation happens anyway.

    Bad Example (Overuse of useMemo):

    const name = useMemo(() => "Akshay", []); // ❌ No need to memoize a static value
    

    👉 In this case, useMemo is redundant.

    4. Can useMemo be used with API calls?

    No, useMemo should not be used for API calls because:

    • useMemo runs during rendering (not after).
    • API calls should be handled using useEffect instead.

    Use useEffect instead:

    useEffect(() => {
      fetchData();
    }, []);
    

    5. What is the difference between useMemo and useCallback?

    FeatureuseMemouseCallback
    PurposeMemoizes return valueMemoizes function reference
    ReturnsComputed valueA memoized function
    Used forOptimizing expensive calculationsAvoiding function re-creations
    Exampleconst result = useMemo(...);const callback = useCallback(...);
    useMemo vs useCallback

    🚀 Rule of Thumb:

    • Use useMemo when caching values.
    • Use useCallback when caching functions.

    6. Does useMemo guarantee that the function won’t run on every render?

    No. If dependencies change, useMemo will recompute the value. However, it ensures that unnecessary calculations are avoided when dependencies don’t change.

    Example:

    const value = useMemo(() => expensiveFunction(), [count]); // Recomputes only if count changes
    

    7. How does useMemo help in optimizing child components?

    When passing derived values to child components, using useMemo ensures the value doesn’t unnecessarily change, preventing unwanted re-renders.

    Example:

    const memoizedValue = useMemo(() => computeExpensiveValue(input), [input]);
    <ChildComponent value={memoizedValue} />;
    

    This helps avoid unnecessary re-renders of <ChildComponent>.

    8. How does useMemo help in handling large lists efficiently?

    For large lists, useMemo helps optimize data processing.

    🔹 Without useMemo (Re-renders on every state change)

    const filteredItems = items.filter(item => item.includes(searchTerm));
    

    🔹 With useMemo (Caches results unless items or searchTerm change)

    const filteredItems = useMemo(() => {
      return items.filter(item => item.includes(searchTerm));
    }, [items, searchTerm]);
    

    🚀 Faster rendering, better performance!

    9. What are some real-world use cases of useMemo?

    Optimizing Computation-Heavy Functions (e.g., sorting, filtering, large dataset calculations)
    Ensuring Referential Equality (e.g., avoiding unnecessary renders in React.memo components)
    Reducing Recomputations in Forms (e.g., validation checks)
    Optimizing Redux Selectors (memoizing computed state values)

    10. How does useMemo compare with React’s built-in optimizations?

    • useMemo prevents unnecessary recomputation within a component.
    • React.memo prevents unnecessary re-renders of child components.
    • Best practice: Use React.memo with useMemo for better performance.

    🔹 Example of using both:

    const memoizedValue = useMemo(() => computeHeavyTask(), [dependency]);
    const MemoizedChild = React.memo(ChildComponent);
    <MemoizedChild value={memoizedValue} />;
    

    🚀 Boosts performance significantly!


    Final Thoughts 💡

    Using useMemo correctly can significantly optimize React applications, but overusing it can lead to unnecessary complexity. Follow best practices:
    ✅ Use it only for performance-critical computations.
    ✅ Avoid using it for simple values.
    ✅ Combine it with React.memo for better rendering optimizations.


    Read other awesome articles in Medium.com or in akcoding’s posts.

    OR

    Join us on YouTube Channel

    OR Scan the QR Code to Directly open the Channel 👉

    AK Coding YouTube Channel

    Share with