JAVASCRIPT

Optimize Expensive Calculations with useMemo Hook

Learn how to use React's useMemo hook to prevent re-running expensive calculations on every render, improving your component's performance significantly.

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

function ExpensiveCalculationComponent({ value }) {
  const [count, setCount] = useState(0);

  const expensiveResult = useMemo(() => {
    console.log('Performing expensive calculation...');
    let result = 0;
    for (let i = 0; i < 100000000; i++) {
      result += value;
    }
    return result;
  }, [value]); // Recalculate only when 'value' changes

  return (
    <div>
      <p>Value: {value}</p>
      <p>Expensive Result: {expensiveResult}</p>
      <p>Count: {count}</p>
      <button onClick={() => setCount(c => c + 1)}>Increment Count (Triggers re-render)</button>
    </div>
  );
}

export default ExpensiveCalculationComponent;
How it works: The `useMemo` hook memoizes the result of a function call. It takes a "create" function and a dependency array. React will only re-execute the "create" function and recalculate the value if any of the dependencies in the array change. In this example, `expensiveResult` is only recomputed when `value` changes, not when `count` updates and causes a re-render of the component.

Need help integrating this into your project?

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

Hire DigitalCodeLabs