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

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 4 years ago

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.

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.

egghead
egghead
~ 7 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today