Write a stateful Component with the React useState Hook and TypeScript
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.
Duration
2 min
Access
Free
Transcript
Available
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.
Video Transcript
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.
Duration
2 min
Access
Free
Transcript
Available
Course lesson
Write a stateful Component with the React useState Hook and TypeScript
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.