React State

·

2 min read

State allows you to store one or more properties of a component. State can be used in a class component but not in a functional component. (However, you may use Hooks inside a functional component.)

In the example below, Student is a component while the name is a property of the component. The "this.state" in the constructor allows you to store one or more properties of the Student. You can just add a comma and another property to the student if you wish to do so.

/*State is initialized in the constructor*/
class Student extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: "Isaac"}; 
  }
  /*State can be used as an object with the this.state.propertyname syntax*/
  render() {
    return (
      <div>
        <h1>My name is {this.state.name}</h1>
      </div>
    );
  }
}

ReactDOM.render(<Student />
  , document.getElementById('root'));

Note: In render, the "this.state.name" must be within curly brackets or else it would just print out "this.state.name".

The State or properties of a component can be changed using setState() which changes its value. The setState() function, an API method that causes a shallow merge between the current and previous state. The component re-renders whenever the state changes. States may change due to either system-generated events or user actions.

class Student extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: "Isaac",hobby: "collecting Beyblade"};
  }
  changeHobby = () => this.setState({hobby:"watching Anime"});
  render() {
    return (
      <div>
        <h1>My name is {this.state.name}. {this.state.name}'s hobby is {this.state.hobby}.</h1>
        <button type="button" onClick={this.changeHobby}>Change Hobby</button>
      </div>
    );

  }
}
ReactDOM.render(<Student />
  , document.getElementById('root'));

Local state is a characteristic only available to class components.

React's State Conventions can be found at: