Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Write a stateful Component with the React useState Hook and TypeScript

    Shawn WangShawn Wang
    reactReact
    typescriptTypeScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    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.