Search code examples
javascriptreactjssetstate

why does the setstate callback function need to be an arrow function?


take this scenario

this.setState({ number: newNumber}, () => console.log(number))

and then this one:

this.setState({ number: newNumber}, console.log(number))

the first one (with the arrow) correctly logs the new state, the second (without the arrow) seems to console.log it one step behind.

why does the arrow function cause it to be correct in the setState callback?


Solution

  • Because, the second parameter inside setState is a callback function. But this is not a callback:

    console.log(number)