useMemo
React’s useMemo Hook returns a memoized value.
Consider memoization to be the process of caching a value such that it does not have to be computed.
The useMemo Hook only runs when one of its dependencies is updated.
This can boost performance.
The useMemo and useCallback hooks are similar. The primary distinction is that useMemo returns a memoized value, whereas useCallback returns a memoized function. The useCallback chapter contains further information.
Performance
The useMemo Hook can be used to prevent expensive, resource-intensive routines from running inefficiently.
In this example, we have a costly function that is executed on each render.
When you change the count or add a todo, there will be a delay in execution.
Example:
A poor-performing function. The expensiveCalculation function runs on every render.
----- Example MUKAVA ----
Notice that we are destructuring useState from react because it is a named export.
For more information on destructuring, see the ES6 section.
Use useMemo
To address the performance issue, we may use the useMemo Hook to memoize the expensiveCalculation function. This will cause the function to run only when necessary.
We can wrap the expensive function call with useMemo.
The useMemo Hook allows a second parameter for declaring dependencies. The expensive function will only run if its dependencies change.
In the following example, the expensive function will run only when the count changes, not when new todos are added.
Example
Performance example with the useMemo Hook: