From the course: React Hooks

Working with the dependency array - React.js Tutorial

From the course: React Hooks

Start my 1-month free trial

Working with the dependency array

- [Instructor] As we saw, every time we change the state, this useEffect call fires, but there's something that can help us out with this. So let's go ahead and pass another argument to this useEffect function, and the argument is just going to be an empty array. Notice how the name changes in the dom, but the effect is not called. So when we pass an empty array, it means that the effect will only fire once, on first render. You also can pass the name of the variable in here. So I could say name, and then when I change the winner, it will follow up by changing the document title. So this is particularly useful if you're dealing with more than one state variable. I'm going to change the document title to a console log message, and then I'll say celebrate name. We'll add another useEffect here. This will take in another function. And this time we'll say console.log, the user is, and we need to create another state variable, too. We'll call these admin and setAdmin, and then the initial state will be false. So this console log message is going to say the user is. We'll use a template here and we'll check the value of admin. If it's admin, we'll say admin. And then if not, we'll say not admin. Okay, so let's go back. And now we have two different state variables. Let's also add another paragraph and another button. So here on line 30, if it's an administrator, then return logged in. Otherwise, return not logged in. And then this button will say login. And then onClick should call that setAdmin function to change the state to true. Okay. So we have a lot of stuff going on here, and what we're noticing right away is that these have fired, these useEffect calls have fired on first render, but let's go ahead and remove this dependency array from our first useEffect. So I'll give that a save, celebrate Jan, user is not admin. So let's click the first one. We see the new state, celebrate Will, but we're still getting this message, too. So my desired effect here, no pun intended, is that if I change the winner, I only want to call this useEffect. So that's where the dependency array comes into play. We'll say, call this one any time the name changes. And then the second one here, we'll say call this one any time the admin changes. So now I change the winner, and we just logged celebrate Will. I changed login, and it just logs the second useEffect. So this dependency array is really useful. We don't want to be running code that we don't have to be. We want to be really specific about which effects should be called when, and we can help do so with this dependency array.

Contents