Why does React have to use setState for state update?

Viewed 4804

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 Answers

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.

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?

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.

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

Related