Save 45% for a limited time.

Get access to all courses and lessons on egghead today.


    Use the useState React Hook

    Kent C. DoddsKent C. Dodds

    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.

    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.

    Disclaimer: This is currently an alpha feature of React and may change in future versions (thought it's fairly stable).



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    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.