简体   繁体   中英

React setState proper usage

So I read a lot that setState calls are batched and are async, and that one should use the updater function to update state when any value is read from the state in setState .

class App extends React.Component {
  state = { count: 1 }
  handleClick = () => {
    this.setState({ count: this.state.count + 1 }) 
  }

  render() {
    return (
      <div>
        <div>{this.state.count}</div>
        <button onClick={this.handleClick}>Click</button>
      </div>
    )
  }
}

Considering above code ONLY, can someone explain what might go wrong in this case by not using the updater pattern of setState ? Even if setState is called later, this.state will always refer to previous state, which is what we want here.

PS: I know that calling setState multiple times one after the other will cause errors in this kind of scenario because they are async, but that's not the case here.

One reason that you should not do this is setStates async behavior. for example if you had two setStates in a single function you wont get the desired output. consider this:

handleClick(){
    this.setState({
        count : this.state.count + 1
    })
    this.setState({
        count : this.state.count + 1
    })
}

If you log the this.state.count now its value will be incremented only by one, but if you do it like this:

handleClick(){
    this.setState((prevState)=>({
        amount : prevState.count + 1
    }))
    this.setState((prevState)=>({
        amount : prevState.count + 1
    }))
}

you will get correct output.

also

the DOM is not updated as soon as setState is invoked. Rather, React batches multiple updates into one update and then renders the DOM. You may receive outdated values while querying the state object How to NOT React

EDIT : i just saw the last paragraph of your question and seems like my answer is exactly what you said you already know! well in that case i think its just respecting the good practices.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM