Liondancer
Liondancer

Reputation: 16469

Fulling updating setState in reactjs

In the reactjs docs for setState:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

The second (optional) parameter is a callback function that will be executed once setState is completed and the component is re-rendered.

What if I just wanted to update my state, do I create a callback that does nothing?

Upvotes: 1

Views: 101

Answers (2)

Sultan Aslam
Sultan Aslam

Reputation: 6238

As they write setState() does not immediately mutate this.state but creates a pending state transition. because it works in an asynchronous way. So if you want to perform an action immediately after setting state on a state variable then a callback will be useful.

For Example

setState(
  { name: "Hello World" },
  () => console.log(this.state)
);

Upvotes: 2

romseguy
romseguy

Reputation: 1563

The callback is optional so you can do this.setState({ key: value });.

Upvotes: 1

Related Questions