14

Why does react have to update state (tree reconciliation) using setState. And not by simply initializing this.state.color = 'red'; supposing that previous value for color is 'green'.

5 Answers5

13

This is how React is built.

The concept is that you should not change the state mutably, like this:

this.state.color = 'red';

Instead, you should use setState:

this.setState({color: 'red'});

The idea behind that is that in order to track changes in state and than re-render the component according to the changes, you have to use setState, because after setState, the render function is triggered.

Ron F
  • 370
  • 2
  • 14
3

When you use this.state.color = 'red'; you mutate the state, it will not trigger re-render.

this.setState({color: 'red'}) will create a new state and assign it to this.state changing it in an immutable way, thus React will know it has changed and will re-render the component.

It's down to how JavaScript works, all primitive values (number, string, boolean, undefined, null) are copied by value when you type let age = 34 or something similar.

But objects and arrays are copied by reference. You can read more about it here: Is JavaScript a pass-by-reference or pass-by-value language?

codeepic
  • 3,723
  • 7
  • 36
  • 57
2

The use of this.state.color = 'red' will not trigger a re-render, while this.setState({ color: 'red }) will. There are other things to consider.

https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly

Filipe Valente
  • 376
  • 2
  • 7
  • 1
    I don't think this answers the question. The question is *why* this happens, not if. – Chris Nov 01 '18 at 10:40
  • The question is why use one and not the other. One triggers a re-render and doesn't mutate the state directly, the other doesn't. – Filipe Valente Nov 01 '18 at 12:30
2

Another imp reason is using setState returns a new state and does not mutate the original state, which can be passed to a pure component. Since pure component only does shallow rendering of objects if the new state is not returned the component will not re render.

VipuL ShiNde
  • 59
  • 1
  • 6
1

React JS is single way binding so state variable could be changed on setState only so it renders once setState in set.