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'.
The setState() Method State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.
React will then look at the virtual DOM, it also has a copy of the old virtual DOM, that is why we shouldn't update the state directly, so we can have two different object references in memory, we have the old virtual DOM as well as the new virtual DOM.
No! This method is called whenever there is a re-render. So, if we use setState() here that triggers re-render again which leads to an infinite loop. never use setState() here.
Passing in a function into setState instead of an object will give you a reliable value for your component's state and props .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With