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

reactjs

Solution

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.

Problem

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` `vdom1` is created - at `line 4` `vdom2` is created - `vdom1` and `vdom2` are compared - difference is propagated to the actual DOM If this is the case, then mutating `state` at `line3` should not have any effect on what happens at `line4`. 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 ?

Original source

Related problems