Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features
Autoplay

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

    Tomasz ŁakomyTomasz Łakomy
    reactReact

    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.

    Code

    Code

    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
    Transcript

    Transcript

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

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

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

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

    Discuss

    Discuss