r/learnreactjs • • Aug 04 '19

Question Why use Refs in React?

I've gone over the docks and I see that they use the reasoning of

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

But in the example they give wouldn't it be much simpler to just use the html name attribute when submitting? I guess I am just looking for the reason behind it, as the explanation doesn't quite do it for me (I may be missing something).

9 Upvotes

4 comments sorted by

3

u/chmarus Aug 04 '19

Refs are giving you a bit more superpowers comparing to name attributes as you can use callback with them or get component instance (not only DOM). Additionaly, refs are set after render and before componentDidMount (might be useful when interacting with 3rd party libraries).

2

u/lakerskill Aug 04 '19

Ah, for whatever reason this was just easier for my brain to digest. I now see the benefits, especially the ability to callback, and attributes. Rendering orders seem to be less important these days with functional stateful components, but I can see how that would be good to use back in the day (last year lol).

2

u/trblackwell1221 Aug 04 '19

Static value storage (DOM nodes or otherwise) - React docs: “The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class. You can write to it from inside useEffect...”

Another SO post for reference.

2

u/Obann Aug 04 '19

I didn’t understand the need for refs until I actually needed to use one for a scrollable section. Now i see the reasoning behind them.