Transcript from the "React Refs" Lesson
>> Brian Holt: You more or less understand all the features. There are some advanced features on refs, which I will give you the 30 second spiel on refs. For the most part, you should never have to really use refs, unless you're integrating with D3 or a jQuery plugin, or something like that.
[00:00:16] But for the most part, you shouldn't need them.
>> Brian Holt: So just to give you like the briefest of introductions to refs. Let's say I was integrating with jQuery and I needed to have like a handle on this h1 here, right? I can't just query the DOM normally because these elements are constantly being destroyed and recreated and destroyed and recreated.
[00:00:43] So if I query it once, it's gonna change later. So you need to have React give you a handle to one of these things. So you can do a ref here, and what you do is you just give it a little function that says, hey, call this this.h1 or something like that, or myh1 = el like this,
>> Brian Holt: Okay? And now if I say console.log(this.el) up here, or this.myH1.
>> Brian Holt: If you look over here, it actually gives me that H1 there. So that's what refs are for. If you actually need to reference some sort of DOM element that's inside of your React application. Again, if you're not integrating with some other library, you should never have to do this.
[00:01:41] The reason why I show this at the end, a lot of times people ask me when they're starting out with React, it's like hey, I need to query the Dom for this. Or I need to have a handle on this because they're used to that kind of jQuery imperative way of like, take this element and call this method on it right.
[00:01:56] And we're kind of inverting that where we let React handle all of that, and we just say, hey React, given this state, this looks like that, right? So that's why I show this to you at the very, very end.
>> Brian Holt: So that's how you do refs, right there.
[00:02:12] You just give it a function, it'll give you that element, and you just stick it on this.something and then you can reference it in other parts of your application.
>> Brian Holt: So a curious part that you might have noticed about that as well. Notice the first time it does it, it's undefined because it's calling it on the first render pass.
[00:02:33] And when it does render for the first time, it doesn't exist, right? It hasn't rendered out yet. But as soon as I call it the second time, it exists because it's rendered the second time.