Check out a free preview of the full Complete Intro to React, v5 course:
The "Best Practices for Hooks" Lesson is part of the full, Complete Intro to React, v5 course featured in this preview video. Here's what you'd learn in this lesson:

Brian explains why hooks cannot be utilized within control flow statements.

Get Unlimited Access Now

Transcript from the "Best Practices for Hooks" Lesson

[00:00:00]
>> Brian Holt: An absolutely fundamental key thing that I need you to really understand right now with hooks is they never go inside of if statements, and they never go inside for loops or anything like that. Why? So I can't say like, if (something), I can't do this. This is not okay, never do this.

[00:00:25] The way that hooks work is, basically, they're keeping track of the order that you're creating hooks. So if I have another hook underneath this, like for example, like for the animal, and setAnimal. And we'll make this dog or something like that. The way that they're keeping track of each individual piece of state is they're keeping track of the order that you're calling these things in, right?

[00:00:49] So if I call these things out of order or if I have an if statement, and then, let's just imagine [INAUDIBLE], if something
>> Brian Holt: If this is true on the first call and false in the second call, this will be the first thing called, which means that this is going to get location instead of animal, which is going to mess up everything.

[00:01:11] So even if you're ignoring what is in useState, you still have to call useState outside of the if statement, outside of a for loop. So I'm actually gonna introduce you to an EL Synch rule that want to make you do that. But I just want to very much underscore the fact that you cannot put in an if statement and you cannot put in a for loop or really any sort of conditional or unpredictable logic.

[00:01:38]
>> Brian Holt: Inevitably, someone at this point in time is going to ask me like, but what if I'm very careful that it's called in the same order? Just don't, I will find you and then I will shame you. [LAUGH] Just kidding, I don't know, but please don't. It's actually underscored in the docs, so it's just something like just never do it.

[00:01:58] Always make sure that they're outside of that.
>> Brian Holt: And this applies to all hooks, not just useState, all hooks in general. Make sure you are always using use something, right? That's a convention that React, if you use this convention, then the ES can help you enforce some of these rules,