Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: useState() vs useRef()

I’ve gone through the React Docs once.

I’m trying to compare useState() with useRef() in my mind…

Commonalities to both useState() and useRef():

  • Available in functional components only
  • Create static values – value persists between function calls
  • Values are mutable
  • Are scoped within their function component
  • Scope includes other hooks (use’s) within their function component

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 components, ref={} refers to the child component 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 commonalities & differences correct?
  2. Any other commonalities or differences I should be aware of?
  3. From the component that creates the reference (useRef+ref={}), can I both get & set values on the child component (yes, it may/may not be wise to do so)?
like image 792
JustAsking Avatar asked Mar 02 '23 17:03

JustAsking


1 Answers

Basically your comparison is correct, but as already was mentioned in comments they serve different purposes. You just need to know is that useRef basically is syntax sugar:

useRef() is basically useState({current: initialValue })[0]

like image 162
slesh Avatar answered Mar 05 '23 16:03

slesh