1

I'm new to JS and React. Went through the documentation given for setState() and found this here:

For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
setState() does not always immediately update the component. It may batch or defer the update until later.

How exactly does it decide which components are to be updated immediately and which are to be deferred?

More precisely, I have something similar to what is given below... Is it a bad idea to have one common setState() outside and another one depending on the conditions? Would it be better performance-wise to do the second option given below even if it means that there'd be a repetition of code?

// First

this.setState({msg: 'Hello!'});

if (someCondition) {
  this.setState({
    res: true
  });
} else {
  this.setState({
    res: false
  });
}


// Second

if (someCondition) {
  this.setState({
    msg: 'Hello!'
    res: true,
  });
} else {
  this.setState({
    msg: 'Hello!'
    res: false,
  });
}
magikarp
  • 460
  • 1
  • 8
  • 22
  • I'm not sure how React makes that decision, so I think that it would probably be best to make the 2 changes at the same time, to avoid any possible re renders – Luis Gurmendez Mar 13 '20 at 14:42
  • This is pretty inconsequential performance-wise. With batching they will be updated in a very similar way. The risk you run with multiple `setState` calls is mostly limited to when you use the previous state values to determine the new state values. You aren't doing that in this example so it won't matter either way – Brian Thompson Mar 13 '20 at 14:42
  • 1
    Does this answer your question? [Does React keep the order for state updates?](https://stackoverflow.com/questions/48563650/does-react-keep-the-order-for-state-updates) – SuleymanSah Mar 13 '20 at 14:48

3 Answers3

1

You could just do something like:

this.setState({res: !!someCondition})

and if it is dependent upon a state value:

this.setState(prevState => ({ res: !!prevState.someCondition })
ehutchllew
  • 940
  • 8
  • 14
1

setState() is async; those two code blocks will run similarly, since react will batch setStates for optimization; So think about the code readability and maintainability; even though if it was different ( which is not ) you should prefer more readability over mere performance difference which is not even measurable; and always keep this in mind when trying new framework or langauage or anything.. premature optimization is the root of all evil

Mechanic
  • 5,015
  • 4
  • 15
  • 38
-1

From my opinion first would be better because setState will always recieve full new object not and existing one. So changing one value will be better. I am also beginner but i will prefer first or i will use triple dots i.e '{...this.state}' to get copy of existing state.

Devansh
  • 52
  • 7