How to cache computed values with the React useMemo hook?

Estimated read time 2 min read

The useMemo hook in React can be used to cache computed values and avoid unnecessary recalculations. Here’s an example of how to use useMemo to cache computed values:

import React, { useMemo } from 'react';

function MyComponent(props) {
  const { data } = props;

  const sum = useMemo(() => {
    console.log('Computing sum...');
    let result = 0;
    for (let i = 0; i < data.length; i++) {
      result += data[i];
    }
    return result;
  }, [data]);

  const average = useMemo(() => {
    console.log('Computing average...');
    if (data.length === 0) {
      return 0;
    } else {
      return sum / data.length;
    }
  }, [data, sum]);

  return (
    <div>
      <p>Sum: {sum}</p>
      <p>Average: {average}</p>
      {/* rest of your component code */}
    </div>
  );
}

In this example, we define a component called MyComponent that takes a data prop. We use the useMemo hook to cache the results of two computed values: the sum of the values in the data array and the average of the values in the data array.

The useMemo hook takes two arguments: a function that computes the value, and an array of dependencies that trigger the computation when they change. In this example, we pass the data prop as a dependency for both memoized values. Whenever the data prop changes, the memoized values are recalculated.

By caching the computed values with useMemo, we can avoid unnecessary recalculations and improve the performance of our React app. Note that useMemo is not always necessary and should only be used for expensive computations that are likely to be repeated.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply