Reusing a Last Assignment
Learn how to maximize performance with the useMemo hook in React by understanding its behavior in different scenarios and its role in reusing values.
Leveraging useMemo
for optimal performance
Reusing a value and memorizing a value sometimes refer to similar behavior. However, it's worth noting that the useMemo
hook can only remember one value from the past, the last value.
A single JavaScript variable, by default, serves a purpose that, unless overwritten by a new assignment, holds the previously assigned value. So, take caution when reading the word "memo" here.
Have you considered interpreting the term “memo” not as the act of memorizing all values but rather as representing a single value, aligning with React’s intended design? Have you explored classical memorization?
How useMemo
reuses the previous assignment is controlled by a deps
dependency array, and it uses the areDepsEqual
utility function to compare two dependency arrays between the previous and current updates. We will skip the source code here and jump straight to the scenarios that correspond to each dependency array configuration.
Similarly, we get three cases here, no dependency, empty dependency, and some dependencies: