The useMemo
hook is a performance optimization in React which leverages "memoization" under the hood. Memoization is essentially an internal caching mechanism that allows functions to avoid re-computing expensive values when receiving the same inputs.
useMemo
has the same function signature as useEffect
and useLayoutEffect
because it also takes a function and optional dependency array as its arguments. Unlike those hooks, however, the value returned by useMemo
is a memoized value.
Note: The React documentation suggests that you implement your logic with useEffect
first to make sure your application works. Then, you can go back and refactor with useMemo
to improve app performance.
// Hook runs whenever the value of 'a' or 'b' change
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b])
// Receiving input for the first time returns a newly computed value
computeExpensiveValue(1, 2)
// Receiving the same input arguments returns a cached value
computeExpensiveValue
This example isn't that great in my opinion. useMemo() should return a value, shouldn't it? The whole point of useMemo() is to return a previously computed value when there is no change in the dependencies. I feel this article has a better example; https://dmitripavlutin.com/react-usememo-hook/.