How to Use State in React Components with TypeScript

Responses (0)


When you need to store some data that won't be shared across components you can use the local component state.

State in Functional Components#

To use state in functional component use useState hook. This hook returns a tuple of two values. The first one is the current value of the state, the second one is a function to update the state.

You can also increase type-safety declaring what types a state accepts:

State in Class Components#

In class components, you can define a state as a class property called state. With TypeScript, you can declare a type for the state:

The CounterProps type is used to declare what type the properties of this component support. The CounterState type will check the state types at the pre-compile time, so you will know earlier if there is an error.

You don't have to annotate CounterState the second time inside of a component itself, but it allows better type inference when accessing this.state.

Notice the React.Component<CounterProps, CounterState> type. This is the generic React.Component type. It takes two type-parameters that tell TypeScript how to interpret types of component props and state, so TypeScript can derive types of each field in props and the state.

There is no need to mark types fields readonly since React.Component<P,S> already marks them as immutable.

To change state in a class component use the setState method. This method enqueues changes in the state and causes a component to re-render.