Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does useCallback have a semantic guarantee?

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.

like image 225
Nepo Znat Avatar asked Nov 04 '20 17:11

Nepo Znat


People also ask

What is 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.

What is the benefit of useCallback?

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.

What is the difference between useMemo and useCallback?

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.

How does useCallback improve performance?

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.


1 Answers

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.

like image 106
Sam R. Avatar answered Oct 22 '22 04:10

Sam R.