Instructor: Here, I have a simple TypeScript application that renders the div, hello world, to the DOM using React and ReactDOM. We can easily move this div into a stateful component called app by creating a class called app that extends from React.Component.
Within the render function, we return the JSX element as before. You can see that it works as expected. Of course, one big advantage of using components is that you get to use props to change the component behavior.
React.Component takes props as its first generic argument. Let's go ahead and add a prop with the member message of type string. We can use this prop in our render method. As you can see, TypeScript is already complaining about the component being used without providing the required message prop.
Let's fix this by passing in a new message. You can see that this prop is now used. Components that extend from React.Component are called stateful, because they can have their own internal state. React.Component takes a second generic argument, which specifies the type of the state.
Let's go ahead and set up our state with a count of type number. We can initialize the state in our constructor. When adding a constructor to a React component, you get passed initial props, which we simply pass to the super React.Component class.
Now, we set up our initial state to have a count of zero. Finally, we can use this state in other places, like the render method. If we run this example, the initial value of the state shows up as expected.
The key reason for having local state in a component is that you get to manage it inside the component. For example, we can call an increment member function whenever the root div is clicked. Within the increment function, we simply use the parent React component's setState method to implement the count of the current state.
If we go ahead and click the div, you can see that the state changes correctly, causing the component to rerender with the new state. Of course, if you want, you can easily move out the inline type definitions for props and state into appropriately named types.