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

Brian demonstrates using the useState hook to update the state of the previously created search input. A hook is a special function that “hooks into” React features. For example, useState is a hook that allows React state to be added to function components.

Get Unlimited Access Now

Transcript from the "useState Hook" Lesson

[00:00:00]
>> So we're gonna use something called a hook, which is a concept that got released with React 16.8, so in React years, it's very new. But it's actually been around for a decent amount of time now, to the point that basically all of React just runs on hooks, but React was not always written this way.

[00:00:20] So I want you to import { useState } from 'react'. Okay, useState is a hook, the way that you can see a hook is that they always start with use. So if you see useEffect, useLayoutEffect, useImperativeHandle, that's one of them. If you see something that starts with use, you can know this is a hook, that's the naming schema for that.

[00:00:55] Instead of saying const Location here, what I want you to do is we're gonna say const, we'll just comment that out. We're gonna do some destructuring here, {location, setLocation} = useState[''], with our default state. Now you can put Seattle, WA here, I'm just gonna leave it as an empty string.

[00:01:23] So that there's no default location that the user can type in whatever they want there. Okay, and now, this still isn't gonna do anything, right, because we haven't used the setLocation yet, but now we have the ability to mutate location. So let's go ahead and do that now.

[00:01:48] So we're gonna make an onChange handler here. And it's gonna take in an event, which I typically just say (e) here. And then I'm just gonna call setLocation(e.target.value). So I wrote that line right there. So anytime a change event happens on this particular input, it's gonna take that, it's gonna call this function here which we're creating.

[00:02:29] It's gonna take that event, it's gonna pull out the target.value. The target is going to be input, and that's gonna pull up the value of what the input is. And then it's going to call setLocation, which is going to update the state here. Once the state is updated, then React is like, they called setLocation, which I know now means that location has changed, I'm gonna rerender that with the new state.

[00:02:57] So just to prove my point and put location here, but I'm also going to put location right there. Okay, so now over here, if I go over here and refresh, Notice that this is being outputted here. Pretty cool, right? This is a one way data binding, right? So I can have data from here bound to here.

[00:03:32] But it doesn't go the other way. Cool, so you can get rid of this location part here. Let's talk about useState just a little bit more. UseState depends heavily on the order that it's called. So if I have five hooks in a row, it's gonna say that the first hook is location, the second hook is animal, the third hook is breed, right?

[00:03:59] And it's gonna call it, so you have to call them in the same order every single time. So generally not a problem, except, do not have conditional hooks. So I cannot say if (something) { const [hook, setHook] = useState();. This, massive no-no, right? Because now I have a variable amount of hooks being called.

[00:04:30] And so if I have another hook after this, const [animal, setAnimal], = useState. Now, depending if something is true or not, this will be something else. And this will get whatever was in here, wasn't intended for something else. So if you see your hooks are not being set to the correct thing and wildly something you don't expect, it might be something like this.

[00:05:01] Generally just, rules of thumb, don't put them in if statements, don't put them in loops. If you don't do that, you're never gonna have a problem. I never have a problem with it, we're actually about to set up an ESLint rule to make sure that you don't do this.

[00:05:17]
>> On the website in code example you have updateLocation instead of setLocation?
>> I do, that's just variable naming.
>> And then, Someone put a console.log in a block of the function block. And then as you were typing, rerendering, and it wasn't running the console.log all the time.

[00:05:38] So they're curious what was going on there.
>> Sure, so if you do something like console.log(location), So it depends on the state of your computer, the state of the background, how React is running, but sometimes it will batch those, right? So if you get multiple things working all together at once, sometimes React is like, cool, I can get this.

[00:06:05] And it'll put multiple locations or sets down into one readout. You can see here it's running mine every single time. But you can't depend on how frequently React is going to render, so don't depend on how frequently React is going to rerender. Don't depend on how it's gonna batch, don't depend on what order things are gonna run in.

[00:06:27] This is all very important, that's why I'm telling you, don't have side effects, keep your render functions very clean and very fast. Because if you do that, you get a bunch of performance stuff absolutely for free, right? Other frameworks are now adopting hooks, you can use hooks in Vue now, so that's kinda caught on.

[00:06:45] Someone was asking me about updateLocation versus setLocation. I actually started calling everything set, just so I can see at a glance as, okay, that's a hook set function for me. I don't think that's even a common React thing, I think that's just a Brian thing. But it helps me to know that that's what that is.

[00:07:07] But it doesn't matter. The only thing that's matter is if you create a custom hook, which we build later in the course, you do need to call it. Use something, that's really what's important. Do not put hooks inside of if statements or loops, that's hard rule, literally never, it's never appropriate.

[00:07:30] Whatever you provide to useState here, this is going to be the default value of it. So this is where hooks get a little strange in terms of their performance profile. On one hand, JavaScript and modern JavaScript engines are very fast, right, they do a lot of stuff really quickly.

[00:07:49] So an example of something that we're doing that's relatively inefficient, but it's kind of okay. Every time this rerender function gets called, it actually is creating a new function here, right, not crazy ideal. If we were super sensitive performance here, we would do something like const eventHandler = blah.

[00:08:11] Actually we can't even do that, cuz here you have to have location. And it's holding on to the correct setLocation via closure, right? So actually, this wouldn't work. But, even though the fact that we are kind of churning through a decent amount of memory here, especially if this will be rerendered fairly frequently, fine.

[00:08:34] I would wait for that to become a problem if we did any sort of memoization or anything like that. There are things that you can do to prevent this from rendering more frequently than it needs to. But for now, we're just gonna ignore and just say, I'm typing a ton here and I'm not feeling any performance problems, it's fine, don't worry about it.

[00:08:55] So onChange is a specific name here, it's basically you can make any sort of event handler here that you need to. So you can see here that actually React will autocomplete for onBlur, OnClick, onClickCapture, onCompositionStart, onCopy, onCut, right? You do all that here, and they're just normal, they're actually React synthetic events.

[00:09:16] So React actually imitates what the normal event object looks like. And then intercepts a lot of that so that React can handle before the browser does, because React can do it faster than the browser. But suffice to say that they imitate the normal API, so you can just look at the MDN event page, and that's fine.

[00:09:35] So let's talk about this for a second, this is called a controlled form. And this is actually a bad idea, the way that we're doing it. So what you could actually do instead is you could just make this have no change handler and no value, and refresh, now this works again, right?

[00:09:57] We're not using our location here. But here, onSubmit, we could just capture the entire event, pull everything out of the form and submit it, right? And use it just like a normal HTML form. That's called an uncontrolled form, or an uncontrolled input, this input is now uncontrolled, cuz React isn't doing anything to it.

[00:10:20] If you have no validation, or trickery that you need to pull with your forms, just do that. I'm showing you this so I can show you how hooks work. And sometimes this is necessary, right, if you're doing like, they have a valid password, or they're giving you a valid zip code, then this would be very important to you and you'd have to do a controlled input.

[00:10:46] But not everything needs it, most things don't need it. Most time you're just taking someone's name or something like that, that's a controlled form. So let's go add one more ESLint rule.