6

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?

1

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.

0

Abstracting state for audio/video would be a good example:

video: {
            readyState,
            networkState,
            error: error || networkState === 3,
            // TODO: This is not pretty. Doing device detection to remove
            // spinner on iOS devices for a quick and dirty win. We should see if
            // we can use the same readyState check safely across all browsers.
            loading: readyState < (/iPad|iPhone|iPod/.test(navigator.userAgent) ? 1 : 4),
            percentagePlayed: getPercentagePlayed(restState),
            percentageBuffered: getPercentageBuffered(restState),
            ...restState
        }

References

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.