Reputation: 670
I'm currently learning React / Hooks, and I wonder what is the difference between these, if any:
const [myRef, _dummy] = useState({current: 0});
const myRef = useRef(0);
(_dummy
will never be used).
As I understand it, myRef
can be used exactly the same way whatever the declaration we choose.
Is that true? If yes, is useRef
simply a syntactic sugar?
Upvotes: 0
Views: 226
Reputation: 153
They are not equivalent. When you update a state by calling setState you will trigger a rerender. However, when you update a ref, there will not be a rerender. This is because refs are intended to be mutable and not tied to the state of the component.
I'm assuming you are never going to change the value (as indicated by your dummy variable), in which case the two forms along with const myRef = {}
are identical in practice but not semantically.
Upvotes: 1
Reputation: 82136
In the example you've given, no, there is no difference
If yes, is useRef simply a syntactic sugar?
No, there is a fundamental difference in that calling _dummy
(i.e. setting the state) would cause a render where as setting the ref value would not.
Upvotes: 0