Bob5421
Bob5421

Reputation: 9073

Difference between this two reactjs setState behavior

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

Upvotes: 0

Views: 40

Answers (1)

Arun Kumar
Arun Kumar

Reputation: 355

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.

Upvotes: 1

Related Questions