Home > Enterprise >  Should one combine setState statements when possible?
Should one combine setState statements when possible?

Time:07-27

Trying to optimize my React app… should one combine setState statements when possible or it is best practice to keep them separate?

setLength(10)
setLengthPercentage(10)
setMarks(["foo", "bar"])

vs

setAll({
  length: 10,
  lengthPercentage: 10,
  marks: ["foo", "bar"],
})

Which is best practice?

CodePudding user response:

Both approaches often work fine, but React recommends:

We recommend to split state into multiple state variables based on which values tend to change together.

So if you will always call setLength, setLengthPercentage, and setMarks together, putting them into a single state variable makes sense. If you might update one but not all at once, it could be easier to have separate states.

Using a single object for state really shines when you have a lot of similar stateful values that get updated with similar logic - for example, in a form with many fields, having a single state object can reduce much of the boilerplate that'd otherwise be required.

Still, it's completely up to you, based on how you'd like the code to look. There are no hard and fast rules.

  • Related