Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty Dependencies with useMemo or useCallback VS useRef

In this GitHub issue I essentially proposed changing:

x = useCallback( ... , []);

To:

x = useRef( ... ).current;

The two are the same but with useRef React doesn't compare the dependencies.

For which a reply came with a question:

Is there ever a situation where a dependency-less useMemo or useCallback would be a better choice than useRef?

I can't think of one, but I may have overlooked some use-cases.

So can anyone think of such situation?

like image 822
Izhaki Avatar asked Nov 11 '19 23:11

Izhaki


People also ask

What is the difference between useRef and useMemo?

useRef can be used to store local mutable value in a component. It doesn't participate in rerendering (unline state data). useMemo is used to memoize (like we do in Dynamic Programming, concept wise) and skip recalculation.

Does useCallback need a dependency?

The useCallback hook is used when you have a component in which the child is rerendering again and again without need. Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed.

What is the difference between useRef and useCallback?

useRef - The Reference Hook For Unmonitored Things. useCallback - The Next Level of Your Callback Function! The Difference Between useMemo And useCallback.

Which cases you should use useRef?

The useRef Hook allows you to persist values between renders. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.


2 Answers

Per React Hooks API documentation:

Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render ... Using a callback ref ensures that even if a child component displays the measured node later (e.g. in response to a click), we still get notified about it in the parent component and can update the measurements.

You can read more about it here and here.

like image 71
Rasuna Khatami Avatar answered Sep 18 '22 07:09

Rasuna Khatami


While you can use useRef to emulate useCallback or with an empty dependency, You cannot use it for all possible scenarios of useCallback which is to rememoize when any of the dependency changes.

Also It won't make much of a performance difference if you use useCallback with empty dependency or useRef since it doesn't have to perform any heavy comparison.

Also if you change the function implementation a bit so that you have to recreate it on a particular param change, you can simply update the implementation with useCallback and add in the extra param as dependency. However if you implement it with useRef, you have to revert back to useCallback

like image 24
Shubham Khatri Avatar answered Sep 20 '22 07:09

Shubham Khatri