1

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?

MiniGunnR
  • 5,590
  • 8
  • 42
  • 66
  • 1
    https://stackoverflow.com/questions/37661166/what-do-function-parameter-lists-inside-of-curly-braces-do-in-es6 – epascarello Dec 21 '17 at 17:45
  • @epascarello Thanks. Is state automatically passed to the function? Because if I understand correctly I have to pass the object to the function if I don't destructure. But I'm passing no parameters when i access count from `this.state.count`. – MiniGunnR Dec 21 '17 at 17:49

1 Answers1

6

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.

Sidney
  • 4,495
  • 2
  • 18
  • 30