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:

  1. Are the above monalities & differences correct?
  2. Any other monalities or differences I should be aware of?
  3. 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:

  1. Are the above monalities & differences correct?
  2. Any other monalities or differences I should be aware of?
  3. 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)?
Share Improve this question edited Mar 8, 2020 at 22:02 Emile Bergeron 17.4k5 gold badges85 silver badges131 bronze badges asked Mar 8, 2020 at 21:57 JustAskingJustAsking 1491 silver badge11 bronze badges 1
  • 1 Both are used for different purposes, there is no parison per se – Anurag Srivastava Commented Mar 8, 2020 at 22:01
Add a ment  | 

1 Answer 1

Reset to default 7

Basically 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