React useMemo Hook

  • useMemo is a React hook that memoizes the result of a computation, preventing unnecessary recalculations on every render.

Purpose

  • Useful when there's a costly computation that doesn't need to be recalculated on every render.
  • Optimizes performance by memoizing the result of the computation until its dependencies change.

Syntax

  • Import useMemo from the 'react' library.
  • Use useMemo with a callback function and a dependency array to memoize the result.
import React, { useMemo } from 'react';

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

Memoized Value

  • Use useMemo to memoize the result of a computation.
import React, { useState, useMemo } from 'react';

const MemoizedValueExample = () => {
  const [count, setCount] = useState(0);

  // Without useMemo, computeExpensiveValue would be recalculated on every render
  const expensiveValue = useMemo(() => computeExpensiveValue(count), [count]);

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

const computeExpensiveValue = count => {
  // Expensive computation logic
  console.log('Calculating expensive value...');
  return count * 2;
};

Memoized Component

  • Use useMemo to memoize a component, preventing unnecessary re-renders.
import React, { useState, useMemo } from 'react';

const ExpensiveComponent = ({ value }) => {
  // Expensive component logic
  console.log('Rendering expensive component...');
  return <p>Expensive Value: {value}</p>;
};

const MemoizedComponentExample = () => {
  const [count, setCount] = useState(0);

  // Without useMemo, ExpensiveComponent would be re-rendered on every parent render
  const memoizedComponent = useMemo(() => <ExpensiveComponent value={count * 2} />, [count]);

  return (
    <div>
      <h2>Example: Memoized Component</h2>
      <p>Count: {count}</p>
      {memoizedComponent}
      <button onClick={() => setCount(prevCount => prevCount + 1)}>Increment</button>
    </div>
  );
};

 

Summary

useMemo is valuable when dealing with expensive computations or components to optimize performance by avoiding unnecessary recalculations or re-renders.