JAVASCRIPT

Optimizing Performance with useMemo for Expensive Computations

Optimize your React components by memoizing expensive calculations using the `useMemo` hook. Prevent unnecessary re-renders and improve performance for computationally intensive tasks.

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

const factorial = (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);

  // This calculation is expensive
  const memoizedFactorial = useMemo(() => {
    console.log('Calculating factorial...');
    return factorial(number);
  }, [number]); // Only re-calculate when 'number' changes

  return (
    <div>
      <h2>Factorial Calculator</h2>
      <input
        type="number"
        value={number}
        onChange={(e) => setNumber(parseInt(e.target.value) || 0)}
        min="0"
      />
      <p>Factorial of {number} is: {memoizedFactorial}</p>
      <hr />
      <button onClick={() => setIncrementor(incrementor + 1)}>
        Increment Other State ({incrementor})
      </button>
      <p>This button increments a separate state value. Notice 'Calculating factorial...' 
         only logs when the 'number' input changes, not when 'incrementor' changes.</p>
    </div>
  );
}

export default FactorialCalculator;
How it works: This snippet demonstrates how to use the `useMemo` hook to prevent expensive computations from running on every re-render. The `factorial` function is computationally intensive. By wrapping its execution within `useMemo` with `number` as a dependency, the factorial is only recalculated when the `number` state changes. Changes to other unrelated states, like `incrementor`, will cause a re-render but will not trigger the factorial calculation again, significantly 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