Reactâs useMemo Hook can be used to optimize the computation costs of your React function components . We will go through an example component to illustrate the problem first, and then solve it with Reactâs useMemo Hook .
Keep in mind that most of the performance optimizations in React are premature. React is fast by default, so every performance optimization is opt-in in case something starts to feel slow.
Note: Donât mistake Reactâs useMemo Hook with Reactâs memo API . While useMemo is used to memoize values, React memo is used to wrap React components to prevent re-renderings.
Note: Donât mistake Reactâs useMemo Hook with Reactâs useCallback Hook . While useMemo is used to memoize values, useCallback is used to memoize functions.
Letâs take the following example of a React application which renders a list of users and allows us to filter the users by their name. The catch: The filter happens only when a user explicitly clicks a button; not already when the user types into the input field:
Even though the filteredUsers donât change when someone types into the input field, because they change only when clicking the button via the search state, the filterâs callback function runs again and again for every keystroke in the input field:
This doesnât slow down this small React application. However, if we would deal with a large set of data in this array and run the filterâs callback function for every keystroke, we would maybe slow down the application. Therefore, you can use Reactâs useMemo Hook to memoize a functions return value(s) and to run a function only if its dependencies (here search ) have changed:
Now, this function is only executed once the search state changes. It doesnât run if the text state changes, because thatâs not a dependency for this filter function and thus not a dependency in the dependency array for the useMemo hook. Try it yourself: Typing something into the input field shouldât trigger the logging, but executing the search with a button click will trigger it.
After all, you may be wondering why you wouldnât use Reactâs useMemo Hook on all your value computations or why Reactâs useMemo Hook isnât the default for all value computations in the first place. Internally Reactâs useMemo Hook has to compare the dependencies from the dependency array for every re-render to decide whether it should re-compute the value. Often the computation for this comparison can be more expensive than just re-computing the value. In conclusion, Reactâs useMemo Hook is used to memoize values.