0

Here is some React/JS code: Is there a difference between:

setState({var1: ...., var2: ...}, this.callback_function);

and

setState({var1: ...., var2: ...});
this.callback_function();

Thanks a lot

Bob5421
  • 7,757
  • 14
  • 81
  • 175
  • 3
    State update are asynchronous. In the second case, the state might not be updated when `callback_function` runs. Please read [React setState not updating state](https://stackoverflow.com/questions/41446560) and https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous and https://stackoverflow.com/a/45186956/3082296 – adiga Apr 10 '21 at 07:42

1 Answers1

1

Yes, they are completely different. The term "callback" refers to the fact that it will be called back after particular event/action.

setState({var1: ...., var2: ...}, this.callback_function);

Here, the state value you will be updated, and then React will call your callback function. You can use the updated state value inside your callback function.

But in your other case:

setState({var1: ...., var2: ...});
this.callback_function();

...since setState is asynchronous, you start the state change, then you call your callback function immediately. You won't see the updated state inside your callback function.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Arun Kumar
  • 355
  • 3
  • 10