The React documentation says the following about useMemo
You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.
For useCallback
there is the following line:
useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).
The word "equivalent" is a bit fuzzy for me and I don't know if that also means that useCallback
does not provide a semantic guarantee.
July 2021) (Learn how and when to remove this template message) Regular semantics is a computing term which describes one type of guarantee provided by a data register shared by several processors in a parallel machine or in a network of computers working together.
useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.
useMemo is very similar to useCallback. It accepts a function and a list of dependencies, but the difference between useMemo and useCallback is that useMemo returns the memo-ized value returned by the passed function. It only recalculates the value when one of the dependencies changes.
Improve your React components performance by using useCallback(). Improving performance In React applications includes preventing unnecessary renders and reducing the time a render takes to propagate. useCallback() can help us prevent some unnecessary renders and therefore gain a performance boost.
useMemo
is equal to useCallback
if the return value of the useMemo
was a function:
// The return value of `useMemo` is calculated every time deps change
useMemo(() => {
return () => { // do some stuff }
}, [deps])
// The function block within `useCallback` is redefined every time deps change
useCallback(() => {
// do some stuff
}, [deps])
I don't know the reason why they made separate hooks for this but I guess they are technically doing the same thing.
As for having a semantic guarantee, I'd say they might do the same thing with useCallback
to "free some memory" but a function memory consumption is less significant than actual data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With