admin管理员组文章数量:1405313
I’ve gone through the React Docs once.
I’m trying to pare useState() with useRef() in my mind…
Commonalities to both useState() and useRef():
- Available in functional ponents only
- Create static values – value persists between function calls
- Values are mutable
- Are scoped within their function ponent
- Scope includes other hooks (use’s) within their function ponent
Differences between useState() and useRef():
- useState triggers re-render, useRef does not.
- useRef can reference child elements (via “ref={}”), useState can’t.
- For child DOM elements, ref={} refers to the DOM element itself.
- For child React ponents, ref={} refers to the child ponent itself.
…And this previous Stackoverflow question adds:
- useState updates it’s value asynchronously, useRef updates synchronously.
So I have 3 questions so far:
- Are the above monalities & differences correct?
- Any other monalities or differences I should be aware of?
- From the ponent that creates the reference (useRef+ref={}), can I both get & set values on the child ponent (yes, it may/may not be wise to do so)?
I’ve gone through the React Docs once.
I’m trying to pare useState() with useRef() in my mind…
Commonalities to both useState() and useRef():
- Available in functional ponents only
- Create static values – value persists between function calls
- Values are mutable
- Are scoped within their function ponent
- Scope includes other hooks (use’s) within their function ponent
Differences between useState() and useRef():
- useState triggers re-render, useRef does not.
- useRef can reference child elements (via “ref={}”), useState can’t.
- For child DOM elements, ref={} refers to the DOM element itself.
- For child React ponents, ref={} refers to the child ponent itself.
…And this previous Stackoverflow question adds:
- useState updates it’s value asynchronously, useRef updates synchronously.
So I have 3 questions so far:
- Are the above monalities & differences correct?
- Any other monalities or differences I should be aware of?
- From the ponent that creates the reference (useRef+ref={}), can I both get & set values on the child ponent (yes, it may/may not be wise to do so)?
- 1 Both are used for different purposes, there is no parison per se – Anurag Srivastava Commented Mar 8, 2020 at 22:01
1 Answer
Reset to default 7Basically your parison is correct, but as already was mentioned in ments they serve different purposes. You just need to know is that useRef
basically is syntax sugar:
useRef() is basically useState({current: initialValue })[0]
本文标签: javascriptReact useState() vs useRef()Stack Overflow
版权声明:本文标题:javascript - React: useState() vs useRef() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744259906a2597661.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论