Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use the useState React Hook

    Kent C. DoddsKent C. Dodds

    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.



    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: 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.

    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.

    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.

    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.

    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.