Search
⌘K
    to navigateEnterto select Escto close

    Use Class properties instead of declaring state in constructor

    Using class properties instead of declaring state in constructor

    In react we use state variables in class components and we set the initial state values using constructor function.

    1class App extends Component {
    2  constructor(props) {
    3    super(props);
    4
    5    this.state = {
    6      name: this.props.name,
    7    }
    8  }
    9}

    We can then access the state variables using this.state and update the state variables using this.setState.

    1// Access the state variable
    2this.state.name;
    3
    4// Update state variable
    5this.setState({ name: 'John Wick'});

    When using Babel plugin that enables class properties we can skip the use of a class constructor. We can rewrite the App class component without using constructor as:

    1class App extends Component {
    2  state = {
    3    name: this.props.name,
    4  };
    5}

    We can access or update the state variables as before.

    1// Access the state variable
    2this.state.name;
    3
    4// Update state variable
    5this.setState({ name: 'John Wick'});
    Previous
    Next