Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Should one combine setState statements when possible?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading