JAVASCRIPT

Optimizing Expensive Calculations with useMemo

Optimize React component performance by using `useMemo` to memoize the results of expensive calculations, preventing re-execution on every render when dependencies haven't changed.

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

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

function FactorialCalculator() {
  const [number, setNumber] = useState(1);
  const [incrementor, setIncrementor] = useState(0);

  // useMemo will only re-run calculateFactorial when 'number' changes
  const factorial = useMemo(() => calculateFactorial(number), [number]);

  return (
    <div>
      <input
        type="number"
        value={number}
        onChange={(e) => setNumber(parseInt(e.target.value, 10) || 0)}
      />
      <p>Factorial of {number} is {factorial}</p>

      <hr />
      <button onClick={() => setIncrementor(incrementor + 1)}>
        Increment other state: {incrementor}
      </button>
      <p>This button changes state but doesn't re-calculate factorial.</p>
    </div>
  );
}
How it works: This snippet demonstrates `useMemo` to optimize an expensive `calculateFactorial` function. By wrapping the calculation with `useMemo` and listing `number` as its dependency, the function `calculateFactorial` will only execute when the `number` state changes. Changes to other unrelated states, like `incrementor`, will cause a re-render but `useMemo` prevents the factorial calculation from running again, saving CPU cycles and improving performance.

Need help integrating this into your project?

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

Hire DigitalCodeLabs