react setstate documentation code example

Example 1: set state

class App extends React.Component {

state = { count: 0 }

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

handleDecrement = () => {
  this.setState({ count: this.state.count - 1 })
}
  render() {
    return (
      <div>
        <div>
          {this.state.count}
        </div>
        <button onClick={this.handleIncrement}>Increment by 1</button>
        <button onClick={this.handleDecrement}>Decrement by 1</button>
      </div>
    )
  }
}

Example 2: setstate react js

constructor(props) {
        super(props);
        this.state = {
            isActive: true,
        };
    }

    checkStatus = () => {
        this.setState({		// use this function
            'isActive' : !this.state.isActive,
        });
    }

Example 3: setstate in react

Functional Component
const [counter, setCounter] = useState(0);

setCouter(counter + 1);

Example 4: component did mmount

componentDidMount()

Example 5: react.component

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Example 6: component did mmount

componentDidUpdate(prevProps, prevState, snapshot)