简体   繁体   中英

React, JS - best practices for setState()

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,
  });
}

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 })

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

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 ie '{...this.state}' to get copy of existing state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM