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?
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.
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.
useRef - The Reference Hook For Unmonitored Things. useCallback - The Next Level of Your Callback Function! The Difference Between useMemo And useCallback.
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.
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.
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
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