Complete Intro to React, v5 Run Only Once
This course has been updated! We now recommend you take the Complete Intro to React, v8 course.
Transcript from the "Run Only Once" Lesson
>> Brian: Now, I wanna show you a couple more things about this. What happens if I want this to run when it mounts, so when it first renders and then Never again?
>> Brian: Well, you just given an empty array. This is an array of its dependencies and it's saying, I depend on nothing, right?
>> Brian: So then it's gonna run once, and then this will never update again.
>> Brian: Right? So if you want it run once on what it first creates that's how you do that. This will be useful for things like if you need to integrate with a J query plug in.
[00:00:33] Like when I'm sorry that's happening to you and, or like D3, that's maybe a better example, right? If you have to integrate with D3 and you need to set up all that stuff, right? This is where you would do it.
>> Brian: And then you could give it an empty array, it's like, okay, once this is integrated then don't update this anymore, right?
[00:00:52] And then if you want it to run every single time something updates, get rid of that. So now, if I come over here,
>> Brian: It should,
>> Brian: What is going on here? There we go.
>> Brian: Yeah, I mean you can see here I've created an infinite loop, you can see that I have,
>> Brian: In fact I'm gonna stop that so I don't crush my API.
>> Brian: So don't do that please. Cuz I'm paying that bill. [LAUGH] So what what was happening there is like it's running every time something updates, right? Which means that every time that I call separates, it's causing an update, right?
[00:01:52] Which means that it caught it's scheduled that effect again. Which is then going to update their breeds again, which is gonna schedule another effect, right? Sick of this infinite loop. So that's why actually they enforce this,
>> Brian: Dependencies thing, so you don't get yourself into these situations, right?
[00:02:09] Because if it depends on animal then you should depend on animal being there and via vice-versa, you don't want to cause these infinite loops of update, and then that schedule in another effect.