JAVASCRIPT

Memoize Expensive Calculations with useMemo in React

Learn to optimize performance by using React's `useMemo` hook to cache the results of expensive computations, preventing recalculations on every render.

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

function calculateFactorial(n) {
  console.log('Calculating factorial...');
  if (n < 0) return -1;
  if (n === 0) return 1;
  let result = 1;
  for (let i = 1; i <= n; i++) {
    result *= i;
  }
  return result;
}

function MemoizedCalculationComponent() {
  const [number, setNumber] = useState(1);
  const [otherState, setOtherState] = useState(0);

  // The factorial will only be recalculated if 'number' changes
  const factorial = useMemo(() => calculateFactorial(number), [number]);

  return (
    <div>
      <h2>Factorial Calculator</h2>
      <input
        type="number"
        value={number}
        onChange={(e) => setNumber(Number(e.target.value))}
        min="0"
      />
      <p>Factorial of {number} is: {factorial}</p>

      <hr />
      <p>Other State: {otherState}</p>
      <button onClick={() => setOtherState(prev => prev + 1)}>
        Increment Other State (Triggers Re-render)
      </button>
      <p>
        Notice "Calculating factorial..." only logs when the input number changes,
        not when "Other State" changes.
      </p>
    </div>
  );
}

export default MemoizedCalculationComponent;
How it works: `useMemo` returns a memoized value. It only recomputes the memoized value when one of the dependencies has changed. Here, the `calculateFactorial` function can be computationally expensive. By wrapping its call in `useMemo` with `[number]` as a dependency, the factorial is only recalculated when the `number` state changes. If `otherState` changes, causing the component to re-render, `factorial` will return its previously cached value, avoiding unnecessary heavy computation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs