← Back to all snippets
JAVASCRIPT

Optimize Expensive Calculations with `useMemo` in React

Discover how to use `useMemo` to memoize the result of an expensive function, preventing unnecessary re-computations on every render and boosting your React application's performance.

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

// A simulated expensive calculation function
const calculateFactorial = (n) => {
  console.log(`Calculating factorial for ${n}...`);
  if (n < 0) return -1;
  if (n === 0) return 1;
  let result = 1;
  for (let i = 1; i <= n; i++) {
    result *= i;
  }
  return result;
};

export function FactorialCalculator() {
  const [number, setNumber] = useState(10);
  const [count, setCount] = useState(0);

  // Use useMemo to memoize the result of calculateFactorial
  // It will only re-run 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>

      <button onClick={() => setCount(count + 1)}>Increment Counter: {count}</button>
      <p>This counter updates without re-calculating factorial if 'number' is unchanged.</p>
    </div>
  );
}
How it works: `useMemo` is a React Hook that memoizes the result of a function. It takes a function and a dependency array. React will only re-execute the function and re-compute its result if one of the dependencies in the array has changed. In this example, the `calculateFactorial` function is potentially expensive. By wrapping it in `useMemo`, the factorial is only recalculated when the `number` state changes, preventing unnecessary re-computations when other states (like `count`) update, thus 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