MiniGunnR
MiniGunnR

Reputation: 5800

What is the difference in these two ES6 arrow functions in React?

If I click a button, it calls handleClick which increases the value of the button by 1 from 0. I have made the handleClick code work in two different scenarios. I understand the first, I don't seem to grasp the second one.

I wrote this one. And it works.

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

The tutorial shows this one and it works too.

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

If I change the code to this, this works too.

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

What is the advantage of using the second body of code when it does the same thing but is more complex than the first one?

I understand I am returning an object literal which is basically what I wrote instead of generating it in the first code body. But why am I passing {count} as a parameter when I can keep the parameter empty and just use this.state.count in the body?

Upvotes: 1

Views: 113

Answers (1)

Sidney
Sidney

Reputation: 4775

In React, this.setState() queues the change. It is not guaranteed to happen right away. So the value of this.state.count may have changed by the time setState actually makes the change.

In the second version, you're passing a function to this.setState(). When React is ready to change the state, that function is called, with the current state as an argument. This lets you ensure that the state is incremented correctly.

The React documentation goes into more detail.

Upvotes: 6

Related Questions