jhegedus jhegedus - 1 year ago 120
React JSX Question

React's setState(), data mutation for nested structures, why not modify state directly?

Is the following react code wrong ?

state={ foo: { bar: true } } // line 1
setState(state) // line 2
state.foo.bar = false // line 3
setState(state) // line 4

If yes, why ?

This suggest that it is wrong, but does not explain why ?

I think it is not wrong, for the following reason:

  • at
    line 2
    is created

  • at
    line 4
    is created

  • vdom1
    are compared

  • difference is propagated to the actual DOM

If this is the case, then mutating
should not have any effect on what happens at

In other words:

this should be equivalent code:

state={ foo: { bar: true } } // line 1
setState(state) // line 2
state={ foo: { bar: false } } // line 3
setState(state) // line 4

Is this code equivalent to the one above ?

If not, why not ?

Answer Source

Creating an immutable clone of state is a good idea because of the way state changes are compared in order to optimise rendering.

In lifecycle methods like shouldComponentUpdate, nextProps are passed in and can be compared to this.props.

If you mutate the state directly, then nextProps.prop1 and this.props.prop1 will always be the same and therefore you might not get the expected behaviour.

I'm sure there are other reasons as well, but this one seems like the most straight-forward.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download