How to use the increment operator in React

setState is an async function. React may batch a bunch of setStates together. So the value of this.state.count is the value at the time you make the request.

A better solutions to call a function that gets evaluated at the time the setState gets executed.

this.setState((prevState, props) => ({
    counter: prevState.counter + 1
})); 

from https://facebook.github.io/react/docs/state-and-lifecycle.html


By doing this.state.count++, you mutate the state, because it's the same thing than doing this.state.count += 1. You should never mutate the state (see https://facebook.github.io/react/docs/component-api.html). Prefer to do that instead:

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

Tags:

Reactjs