Empty Dependencies with useMemo or useCallback VS useRef
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.
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
Because the output of the useRef(() => {...}).currentis mutable.
Which can cause weird side Effects in your code.I can change the value of current at any time.https://codesandbox.io/s/confident-monad-vjeuw
That would be the usecase for not wanting to use useRef