useMemo() hook in React as of 16.8.0 can memoized a value for an expensive computation, but note that it has really "short memory".
To see how it works, look at the "console" to see when the expensive function is invoked: https://stackblitz.com/edit/react-ueeptk
const value = useMemo(() => expensiveFunction(a), [a]);
When it already did the calculation for
2, then it won't do it for
2 next time. Likewise for the
However, it really can only memoize one value. If the first time, it did the calculation for
1, and next it did the calculation for
2, it won't remember what the result is for
1 any more. When supplied with
1 again, it will do the calculation again. Example: https://stackblitz.com/edit/react-hpugxu
The behavior is similar to
React.memo(ComponentA), which can memoize a function component result and won't call it to render the React elements again as long as the props, state, and context stay the same.
Top comments (0)