1

Whats the difference between

setState((prevState)=>{return {value:prevState.value+1}},callback)

vs

setState((prevState)=>{return {value:prevState.value+1}},()=>{callback})

I am getting old state in 1st type of setState() in callback function e.g console.log(this.state.value) is printing old state.

a2nineu
  • 37
  • 5
  • Does this answer your question? [What is prevState in ReactJS?](https://stackoverflow.com/questions/54807454/what-is-prevstate-in-reactjs) – Aman Sadhwani Jul 01 '22 at 05:48
  • @AmanSadhwani No, actually I know about prevstate, I just used () instead of passing prevState, I am just confused passing a function to call back parameters. 1st one is accessing old state,2nd one is accessing new updated state. – a2nineu Jul 01 '22 at 05:50

1 Answers1

0
setState((prevState)=>{return {value:prevState.value+1}},()=>{callback})

In the above code, you're using an anonymous function to wrap callback, but callback is not triggered as you expected.

If you want to trigger callback, you need to make it like callback()

setState((prevState)=>{return {value:prevState.value+1}},()=>{callback()})

setState((prevState)=>{return {value:prevState.value+1}},callback)

This is different. You pass callback as a parameter directly, and the callback will be executed in setState internally.


To clarify more how setState calls callback internally, I'd show you a small demo.

const setState = (state, callback) => {
   //TODO: The logic for state
   //and then execute callback
   callback()
}

setState({}, () => console.log('Callback here'))
Nick Vu
  • 14,512
  • 4
  • 21
  • 31
  • Can you explain why callback will be executed in setState internally in the first case? – a2nineu Jul 01 '22 at 06:02
  • You can check my updated answer with a small demo @a2nineu – Nick Vu Jul 01 '22 at 06:15
  • Thank you so much but why console.log will show us old state if we dont wrap it around anonymous function? – a2nineu Jul 01 '22 at 09:04
  • because the anonymous function gets triggered (not `callback` function). If you want to trigger `callback`, you need to explicitly execute it `callback()` @a2nineu – Nick Vu Jul 01 '22 at 09:07