Our First Stateful Component

Learn how to access and define state inside a React component.

State inside a class component can be accessed with the instance property this.state. However, it is encapsulated in the component, and neither parent nor child components can access it.

To define a component’s initial state, we can select from three ways. Two of these are relatively simple. The third is a little more advanced. We’re going to cover the latter when we learn about the lifecycle method getDerivedStateFromProps().

The initial state can be defined by setting this.state. We can do this with the constructor of a class component:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: props.counter,
    };
  }
  render() {
    // ...
  }
}

This can also be done by defining the state as an ES2017 class property. This is much shorter but still requires the Babel plugin @babel/plugin-proposal-class-properties (pre-Babel 7: babel-plugintransform- class-properties):

class MyComponent extends React.Component {
  state = {
    counter: this.props.counter,
  };
  render() {
    // ...
  }
}

Note: Class Property Syntax is supported out-of-the-box by Create React App. As most projects today rely completely or in part on the CRA setup, this syntax is already widely used and common to see in most projects. If you encounter a project where this is not the case, Try installing Class Property Syntax and use this Babel plugin because it reduces the length of your code and is easily set up.

Once the state is defined, we can read its value via this.state. While it is possible to mutate this.state directly, it is actively discouraged.

Get hands-on with 1200+ tech skills courses.