Lesson 8. Optimizing performance with useMemo and useCallback 1. Memoization with useMemo
In this example, our goal is to display the number of prime numbers lower than a given number:
Result
- The
inputstate contains the current value of the input. maxis updated when the user clicks the button; it gets the input's value (input).- The variable
nbcontains the result of a CPU-consuming operation: the number of prime numbers lower thanmax.
This component works perfectly fine on small numbers. But if you enter 1,000,000 in the input and press the button, it can take a couple of seconds to display the result (in a real use case using an async function would be better).
Suppose we change again the value of the input (even without clicking the button). In that case, it still takes a couple of seconds to update what is displayed, making the user interface relatively unresponsive.
The reason is that we recalculate the value of nb at each rendering, even if
the value of max wasn’t changed.
The useMemo hook
The hook useMemo will help us here:
const nb = useMemo(() => {return nbPrimes(max)}, [max])
useMemo takes two parameters:
- A function returning the result of the computation we want to achieve.
useMemowill return the value this function returned. - A dependencies array, similar to the one passed to
useEffect.
Each time one of the values in the dependencies array is changed (and only at
those times), useMemo will execute the function to return its return value.
Here, each time max is updated, we will recalculate the number of prime
numbers lower than it. We don’t if only input is changed.
Result