logo
React Hooks - Interview Questions and Answers
How does useMemo help in performance optimization?

useMemo is a React Hook that plays a crucial role in performance optimization by memoizing the result of a computation. Here's a breakdown of how it works and how it helps:

What is Memoization?

  • Memoization is a technique that stores the result of a function call and returns the cached result when the same inputs occur again.
  • This avoids redundant computations, which can be especially beneficial for expensive or time-consuming operations.


How useMemo Works :

  1. Arguments :

    • useMemo takes two arguments:
      • A function that performs the computation.
      • A dependency array.
  2. Caching the Result :

    • On the initial render, useMemo executes the provided function and stores the result.
    • On subsequent renders, useMemo checks the dependency array.
    • If the values in the dependency array have not changed, useMemo returns the cached result from the previous render, without re-executing the computation function.
    • If the values in the dependency array have changed, useMemo re-executes the computation function, stores the new result, and returns it.


How useMemo Optimizes Performance :

  • Avoiding Expensive Computations :

    • If you have a function that performs a complex calculation or data transformation, useMemo can prevent it from being re-executed unnecessarily.
    • This is particularly useful when the computation depends on props or state that don't change frequently.
  • Preventing Unnecessary Re-renders of Child Components :

    • When you pass a computed value as a prop to a child component, the child component might re-render even if the value hasn't actually changed.
    • By using useMemo to memoize the computed value, you can ensure that the child component only re-renders when the value changes.
    • This is especially helpful when combined with React.memo, which memoizes the entire child component.
  • Reference Equality :

    • useMemo returns a memoized value. This is very useful when passing down values that rely on referential equality to prevent unneeded rerenders. For Example, if you are passing down an object, or an array as a prop. Without useMemo, a new object or array will be generated on every render, even if the contents are the same. This will cause the child component to rerender.

Example :

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

function ExpensiveCalculation({ a, b }) {
  const result = useMemo(() => {
    console.log('Calculating...');
    // Simulate an expensive calculation
    let sum = 0;
    for (let i = 0; i < 100000000; i++) {
      sum += a + b;
    }
    return sum;
  }, [a, b]);

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

function App() {
  const [num1, setNum1] = useState(1);
  const [num2, setNum2] = useState(2);

  return (
    <div>
      <input type="number" value={num1} onChange={(e) => setNum1(parseInt(e.target.value))} />
      <input type="number" value={num2} onChange={(e) => setNum2(parseInt(e.target.value))} />
      <ExpensiveCalculation a={num1} b={num2} />
    </div>
  );
}

export default App;

 

In this example :

  • The useMemo Hook memoizes the result of the expensive calculation.
  • The calculation will only be re-executed when a or b changes.
  • Without useMemo, the calculation would be re-executed on every render, even if a and b remained the same.

By strategically using useMemo, you can significantly improve the performance of your React applications.