Skip to content Skip to sidebar Skip to footer

This.state Inside Setstate Reactjs

So I have some confusion regarding the async nature of setState in ReactJS. As per React docs, you shouldn't use this.state inside setState(). But if I have a counter as a state an

Solution 1:

You have access to prevState from within your setState call:

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

That will allow you to safely increment the current state value.

The React documentation summarises why you cannot rely on this.state to be accurate during update: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

Solution 2:

setState accepts a function as a parameter with previous state as argument. Refacto as follows to avoid competition problems:

onClick = () => {
    this.setState(prevState => ({counter: prevState.counter + 1}))
}

Post a Comment for "This.state Inside Setstate Reactjs"