Categories
React Answers

How to use the React useMemo hook?

Spread the love

To use the React useMemo hook, we call useMemo with a callback to return the value we want and an array with the values to watch to return the result in the callback.

For instance, we write

const MyComponent = () => {
  const computeLetterCount = (word) => {
    let i = 0;
    while (i < 1000000000) i++;
    return word.length;
  };

  const letterCount = useMemo(() => computeLetterCount(word), [word]);
  //...
};

to create the computeLetterCount function that returns some value derived from the word state.

Then we call useMemo with a function that calls computeLetterCount with word to do the computation.

We pass in [word] as the 2nd argument so we return the latest value of the callback with useMemo when word changes.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *