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.