Class Components React Tutorial with setState() – Course #7

Posted by

React Course #7 – React full Tutorial – setState() in Class Components

Welcome to React Course #7 – React full Tutorial on setState() in Class Components

In this tutorial, we will be learning about how to use the setState() method in React class components.

What is setState()?

setState() is a method that is used to update the state of a React component. It is a built-in method provided by React that allows us to update the state of a component and trigger a re-render of the component.

How to use setState() in Class Components

In order to use setState() in a React class component, we first need to define the state of the component using the constructor method. The initial state of the component can be defined inside the constructor by setting this.state to an object that contains the initial state values.


class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <h1>Count: {this.state.count}</h1>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }

  incrementCount = () => {
    this.setState({ count: this.state.count + 1 });
  }
}

In the example above, we have defined a Counter class component that has an initial state with a count value of 0. When the incrementCount method is called, it updates the state using setState() by incrementing the count value by 1.

Conclusion

Using the setState() method is a fundamental concept in React that allows us to update the state of a component and trigger a re-render of the component. By following this tutorial, you should now have a better understanding of how to use setState() in class components in React.