score:9

Accepted answer

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.

score:1

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

score:1

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

score:1

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.

score:2

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?


Related Query

More Query from same tag