0

When we have to update any state which is based on the previous state then it is better to use this.state?

class Counter extends Component {
  constructor(props) {
    super(props)
    this.state = { count: 0 }
  }
  changeCount() {
    this.setState({
      count: this.state.count + 1
    })
  }
}

or it is better to use function?

class Counter extends Component {
  constructor(props) {
    super(props)
    this.state = { count: 0 }
  }
  changeCount() {
    this.setState(prevState => ({
      count: prevState.count + 1
    }))
  }
}

palaѕн
  • 72,112
  • 17
  • 116
  • 136
dx4iot
  • 53
  • 1
  • 8
  • 2
    Does this answer your question? [When to use React setState callback](https://stackoverflow.com/questions/42038590/when-to-use-react-setstate-callback) – norbitrial Apr 17 '20 at 17:10
  • no, I need to know which one is better? – dx4iot Apr 17 '20 at 17:11
  • the second version is guaranteed to be atomic, though in practice i've never saw an problem with referencing `this.state` directly. i hear it can cause problems with many calls to `setState` that can become batched into a single update, but i've never seen it in practice. – r3wt Apr 17 '20 at 17:19
  • @NishantTiwari Posted the explanation, with the official source link – Manish Sundriyal Apr 17 '20 at 17:26

1 Answers1

2

The later one is better. Using prevState is better than using this.state for updating states based on previous state values.

As mentioned here: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

One may not across a situation where the difference is clear. But when working with frequent states updates asynchronously, it will be very difficult to debug. Thus it's not good to rely on the former case.

Manish Sundriyal
  • 611
  • 6
  • 16