React useMemo Hook

useMemo is a hook in React that allows you to memoize a component's output. It takes two arguments: a function that calculates the value to be memoized, and an array of dependencies. The hook will return the memoized value, and will only re-calculate the value if any of the dependencies have changed. This can be useful for optimizing performance in situations where a component's output is expensive to calculate and the component only needs to re-render when certain props or state values change.

import { useMemo } from 'react';

function MyComponent({ data }) {
  const expensiveCalculation = useMemo(() => {
    // This function performs a expensive calculation
    // that takes a long time to complete.
    let result = 0;
    for (let i = 0; i < data.length; i++) {
      result += data[i] * data[i];
    }
    return result;
  }, [data]);

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

In this example, the component MyComponent takes in some data as a prop and performs an expensive calculation that takes a long time to complete. The useMemo hook is used to cache the result of the calculation so that it only needs to be re-computed if the data prop changes. The hook takes in a function that performs the calculation and an array of dependencies (in this case, just data).

When MyComponent renders, the hook will first check if the data prop has changed since the last render. If it hasn't changed, the hook will return the cached result of the calculation without running the function again. If the data prop has changed, the hook will re-run the function and update the cached result. This can greatly improve the performance of the component, especially if the data prop changes frequently or the calculation is very slow.

Please note that useMemo is not only used for mathematical calculation, it can be used on any expensive operations like fetching data from API or something like that.