React - Use State to Toggle an Element

Hey, I am having a problem understanding this challenge. it’s unclear for me for many reasons

first of all what is meant by state updates may be asynchronous ?

and why React may batch multiple setState() calls into a single update. ?

why react may call setState multiple times when doing a single update?

This means you can’t rely on the previous value of this.state or this.props when calculating the next value. So, you should not use code like this: and does this means that when calling the previous value it will already be updated?

Your code so far

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibility: false
    };
    // Change code below this line

    // Change code above this line
  }
  // Change code below this line

  // Change code above this line
  render() {
    if (this.state.visibility) {
      return (
        <div>
          <button onClick={this.toggleVisibility}>Click Me</button>
          <h1>Now you see me!</h1>
        </div>
      );
    } else {
      return (
        <div>
          <button onClick={this.toggleVisibility}>Click Me</button>
        </div>
      );
    }
  }
}

Challenge: React - Use State to Toggle an Element

Link to the challenge:

  1. It just means it doesn’t happen right away.

  2. For performance.

  3. It doesn’t. It can batch multiple updates into a single update pass.

  4. state and props received by the updater function are guaranteed to be up-to-date.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
  updateCountByOne = () => {
    this.setState({ count: this.state.count + 1 })
    this.setState({ count: this.state.count + 1 })
    this.setState({ count: this.state.count + 1 })
    // this.state.count increases by 1, not by 3
  }
  updateCountByThree = () => {
    this.setState(({ count }) => ({ count: count + 1 }))
    this.setState(({ count }) => ({ count: count + 1 }))
    this.setState(({ count }) => ({ count: count + 1 }))
    // this.state.count increases by 3
  }
  render() {
    return (
      <div>
        <button onClick={this.updateCountByOne}>updateCountByOne</button>
        <p>{this.state.count}</p>
        <button onClick={this.updateCountByThree}>updateCountByThree</button>
      </div>
    )
  }
}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.