Become a member
to unlock all features

Level Up!

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


    Add state to functional React component with useState hook without introducing a class

    Tomasz ŁakomyTomasz Łakomy

    Most React developers knows the pain of refactoring a functional component only because we would like to add a state to it.

    In this lesson we are going to learn a new way of handling that - React 16.7 alpha introduces a concept of hooks, which allow us to well... hook into existing React features (such as state) from inside of a functional component. By using a useState hook we introduce state to a Counter component without introducing a class.



    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: We have a simple counter component which takes a count as a prop and displays it. Also, we want to have a button which allows us to update a counter. Counter is a functional component, and it's rendered over here. The usual way of adding state to a counter component would be to change it to a class.

    We're not going to do that. Instead, we are going to use a new hook from React which is called useState. This component's not going to accept a prop anymore. We can remove it from both places. Next, to add state to our functional component, destructure the count, and set count from useState, zero.

    After we save it, we see that the value of count has been set to zero, because this is the default value we've provided to useState call. To use this set count function, we need to attach it to an onClick handler to the button. We're going to do setCount, count plus one.

    Now, we have the desired effect. By default the count is set to zero. Whenever I click the button, the counter is going to be updated. The reason it works is because useState allows us to hook into React features such as state, without transforming the counter component into a class component. It can remain as a functional component.