Write a stateful Component with the React useState Hook and TypeScript

Shawn Wang
InstructorShawn Wang
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 4 years ago

Here we refactor a React TypeScript class component to a function component with a useState hook and discuss how props and state types can be modeled accordingly.

Instructor: [0:00] We have here a stateful Toggle button that toggles between red and green and accepts a default prop. Let's say we want to use Reacts Hooks to do the same thing. How are we going to achieve that?

[0:17] There are no static properties in functions, so the first thing to do is to move the default props out to a separate line. Next, we convert the class into a function. We remove the render method as well as take props inside the function arguments.

[0:45] All event handlers are now variables as well as state. You can wrap all state in React.useState as well as remove all references to "this." That gives us back our working Toggle.

[1:07] Notice that TypeScript is able to infer the types of the state, but you can also give it a hint by passing in a generic to React.useState similarly to how we passed it into React.Component. This is helpful, for example, if you want to specify a union type, and you want your state to be inferred accordingly.

egghead
egghead

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