Javascript – React: Nested object as state vs individual properties

design-patternsjavascriptreactjsstate

Are there any use-cases where a nested object as state is either more optimal/easier to work with than individual properties?

For instance if I wanted to express some user controls for interacting with a photo in state I could write something like so (nested object):

this.state = {
   photoControls: {
      open: false,
      id: null,
      thumbnailUrl: null
   }
}

Or I could also write it this way (individual properties):

this.state = {
   photoControlsOpen: false,
   photoControlsId: null,
   photoControlsThumbnailUrl: null
}

Although I can logically group properties together using a nested-object style of state, it seems to only prove more verbose when trying to update just one, or a couple, of those properties.

This being said, what are the benefits (if any) to using nested objects in state as opposed to using individual properties. I understand that nested-objects might feel more proper, but I can't think of any benefits to them, anyone have any insight?

Best Answer

It depends on likely future development. Creating a separate object for PhotoControls is a waste of time and code if the object is never reused. However, if PhotoControls is likely to be used in another object, then defining it separately is good, but only if the abstraction is really useful. If the Photocontrols object in another object must have attributes that are not relevant in the old context, you may have built a bug trap.

I have often regretted creating sub-objects when they were unnecessary and been very happy to have created them when they were useful. Think about what you might want to do in the future. You won't always be right, but thinking about it ahead of time improves your odds.

Related Topic