Write a stateful Component with the React useState Hook and TypeScript

Shawn Wang
InstructorShawn Wang

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year 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.