Hi, just out of curiosity can useMemo
be used instead of useRef
when doing it as following:
Example:
const ref = useRef(null);
const ref2 = useMemo(() => { current: null }, []);
It looks to me that both refs will be working just fine as DOM ref and as mutable value similar to instance fields in classes. Why then useRef
is implemented differently comparing to useMemo
considering ReactFiberHooks.js code for useRef
and useMemo
?
Thanks!
You could create a ref object this way, but it would be less efficient since useMemo
also tracks and compares dependencies. (Even if you specify an empty dependency array, the underlying data structure for a memo hook has space for the extra value.)
To illustrate this, you can compare the implementation of useRef
:
https://github.com/facebook/react/blob/434770c3b4b94315c789234c27ed9dc2ec8a78ad/packages/react-reconciler/src/ReactFiberHooks.js#L907-L920
To useMemo
:
https://github.com/facebook/react/blob/434770c3b4b94315c789234c27ed9dc2ec8a78ad/packages/react-reconciler/src/ReactFiberHooks.js#L1126-L1156
Since both hooks are used frequently, it's important they perform optimally :smile: so they are implemented different.
You _could_ create a ref object this way, but it would be less efficient since
useMemo
also tracks and compares dependencies. (Even if you specify an empty dependency array, the underlying data structure for a memo hook has space for the extra value.)To illustrate this, you can compare the implementation of
useRef
:
https://github.com/facebook/react/blob/434770c3b4b94315c789234c27ed9dc2ec8a78ad/packages/react-reconciler/src/ReactFiberHooks.js#L907-L920To
useMemo
:
https://github.com/facebook/react/blob/434770c3b4b94315c789234c27ed9dc2ec8a78ad/packages/react-reconciler/src/ReactFiberHooks.js#L1126-L1156Since both hooks are used frequently, it's important they perform optimally 😄 so they are implemented different.
hi, how to format the code like this ?
@yaofly2012 GitHub formats links that way, if you link to a specific file revision and line numbers.
Most helpful comment
You could create a ref object this way, but it would be less efficient since
useMemo
also tracks and compares dependencies. (Even if you specify an empty dependency array, the underlying data structure for a memo hook has space for the extra value.)To illustrate this, you can compare the implementation of
useRef
:https://github.com/facebook/react/blob/434770c3b4b94315c789234c27ed9dc2ec8a78ad/packages/react-reconciler/src/ReactFiberHooks.js#L907-L920
To
useMemo
:https://github.com/facebook/react/blob/434770c3b4b94315c789234c27ed9dc2ec8a78ad/packages/react-reconciler/src/ReactFiberHooks.js#L1126-L1156
Since both hooks are used frequently, it's important they perform optimally :smile: so they are implemented different.