All Articles

Why you should simplify React states

React JS Code

React is not designed to be used with complex nested states. Sure, the internet is full of articles explaining how you can use a fairly complex nested state object with React but unfortunately that kills the beauty of react.

Let’s understand this by an example, consider the following state object:

{
    parent: {
        item_1: 'value_1',
        item_2: 'value_2',
        ...
        item_n: 'value_n'
    }
}
  • What happens if you just change the value of item_1?

    React will not re-render the view because it uses shallow comparison and it will find that parentproperty didn’t change. You should never be mutating the state object directly, just to provide an example.

  • What happens if you re-create the whole parentobject?

    React will think that all children have changed their values and will re-render all of them. Also, it is not good for performance.

So then what is the best way to maintain React state objects?

Keep it simple, silly! The state object should always be simplified to root level attributes. Example:

this.state = {
    item_1: 'value_1',
    item_2: 'value_2'
}