Chooce video playback speed
speed:1

Write a stateful Component with the React useState Hook and TypeScript

InstructorShawn Wang

Share this video with your friends

Send Tweet

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.

This lesson is a Community Resource

A Community Resource means that it’s free to access for all. The instructor of this lesson requested it to be open to the public.

Instructor: 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?

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.

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.

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.