Use the useState React Hook

Kent C. Dodds
InstructorKent C. Dodds

Share this video with your friends

Send Tweet
Published 3 years ago
Updated 3 months ago

React's new hooks feature allows you to use state in function components in a really simple and elegant way. Let's look at a very basic example of a <Counter /> component that uses the useState React hook.

Instructor: [00:00] Here, we have a button that we're rendering with the number zero, and we want to increment this number every time I click on the button. I'm going to extract this, and make a count variable. That count is going to be zero.

[00:12] Then I'm going to import useState from React. This count is actually going to come from a call to useState. Now, useState is going to return an array, and I'm going to destructure that array to get the count out of that array, the first item of the array.

[00:27] Then I'll destructure the setCount function to update that count whenever the button is clicked. We'll add onClick equals this arrow function, to call setCount of count plus one. With that, I now have an incrementing button.

[00:42] Let's go ahead, and we'll just extract this a little bit. We'll call this increment. Increment equals that arrow function, and it still works just as well. In review, to make this work, we used the useState hook from React, and we destructured the array that comes back from that useState hook, which gives us count and setCount.

[01:03] Then we rendered out the count, and then set the onClick handler for the button to increment, which calls setCount for count plus one. Then we could add two. We could also initialize this to four. Now, we're starting at four, and jumping by twos.

msm1089
msm1089
~ 3 years ago

Great videos Kent!

Just wondering about the message I see below the playlist tho, about these being outdated:

This lesson is outdated. Click here to find out about changes you should be aware of. React 16.7.0-alpha.0 was recently released and with it comes a set of experimental hooks and features. Use these with caution as they are likely to change in the near future.

Does this actually apply? I am confused about it since this is a very recent set of videos right?

Kent C. Dodds
Kent C. Doddsinstructor
~ 3 years ago

That's a generic message. What it should say is that this is alpha and therefore prone to changing.