Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does React have to use setState for state update?

Tags:

reactjs

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'.

like image 580
Sushree Moharana Avatar asked Nov 01 '18 09:11

Sushree Moharana


People also ask

Why do you need to use setState () to update state in React?

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.

Why we cant update state directly in React?

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.

Do you have to use setState in React?

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.

Why is it recommended to use the setState function instead of directly updating your application state like?

Passing in a function into setState instead of an object will give you a reliable value for your component's state and props .


1 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.

like image 178
Ron F Avatar answered Oct 06 '22 08:10

Ron F