useMemo in React

Expert-Level Explanation

useMemo is a React hook that returns a memoized value. It's used to optimise performance by memorising expensive calculations. The hook only recalculates the memoized value when one of its dependencies has changed. This avoids unnecessary calculations on every render.

Creative Explanation

Imagine useMemo as a smart calculator that remembers the result of a complex calculation. When you ask it to redo the calculation with the same inputs, it gives you the stored result instead of recalculating it, saving time and energy.

Practical Explanation with Code

Example of using useMemo:

import React, { useMemo } from 'react';

function ExpensiveComponent({ num }) {
  const expensiveCalculation = useMemo(() => {
    return calculateExpensiveValue(num);
  }, [num]);

  return <div>Result: {expensiveCalculation}</div>;
}

function calculateExpensiveValue(num) {
  // Perform a calculation that is resource-intensive
}

In this example, expensiveCalculation is recalculated only when num changes.

Real-World Example

In a financial application, useMemo can be used to calculate complex financial data such as projected earnings or compound interest. These calculations, which might be CPU-intensive, are only recomputed when the relevant input values (like the principal amount or interest rate) change.