Allan Chua
Allan Chua

Reputation: 10175

Is it a good idea to use the "setState" function in JavaScript even if the previous state is irrelevant?

I basically understand the difference between object and function setState in React in terms of atomicity and resiliency to batch updates.

// Subject to batching issues.
this.setState({
  x: this.state.x + 5
});

Or should I use:

// Atomic since previous state is known
this.setState((state, props) => {
  x: state.x + 5
});

However, I wonder what could be the advantages of using functional setState if previous state is irrelevant.

this.setState(() => {
  food: "Bars"
});

Upvotes: 0

Views: 126

Answers (2)

Nagarjuna
Nagarjuna

Reputation: 61

setState with object as parameter does shallow comparison with previous state.

If your value is dependent on previous state it is good practice to use setState with function(as setState is async operation) otherwise just pass Object as parameter.

There should not be performance issue in either case.

Upvotes: 1

Matt Way
Matt Way

Reputation: 33171

I don't think there are any advantages, as they are basically the exact same function call, just using an object vs a function. So if your update doesn't depend on the current state or current props, then use an object. If it does require previous knowledge, use the function type.

Both versions also allow you to use a callback to access the state after the state has changed, so there is no difference in abilities either.

The only reason I might use the function version everywhere is just for consistency, or in situations where I am currently not using the previous state, but might in the future.

Upvotes: 2

Related Questions