Gaurang Shah
Gaurang Shah

Reputation: 12910

ReactJS difference between setting state directly and through method argument

I have started learning ReactJS and realize that there are two way I can change the state. Both works fine without any error or warning.

What is the main difference? is there a reason or need I should use second version?

consider I want to modify following state on each click

this.state = { count: 0 } 

First Version

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

Second Version

handleClick = () => {
    this.setState(prvState => {
        return {
            count: prvState+1
        }
    })
}

Upvotes: 2

Views: 55

Answers (2)

Ana Liza Pandac
Ana Liza Pandac

Reputation: 4871

If you are setting the next state value based on the previous state value then passing in a function (second version) as the first parameter of this.setState instead of an object is the recommended solution.

handleClick = () => {
    this.setState(prvState => {
        return {
            count: prvState+1
        }
    })
}

The reason is that this.state may be updated asynchronously and that's why you should not rely on their values for calculating the next state.

In the first version, there's a high possibility that the value of count is incorrect especially once your application gets bigger.

Upvotes: 3

inyono
inyono

Reputation: 424

If you rely on the previous state (like in your case you need the previous counter value), the second approach is preferred. It guarantees that prvState holds the current state. This is important if you have two setState modifying the state in the same render loop (remember that React may batch multiple setState calls together), e.g.

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

has the problem that the count gets only incremented once. While

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

guarantees that it gets incremented twice as intended (independent of the order the setState are handled by React)

Upvotes: 1

Related Questions