Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will happen if I use setState() function in constructor of a Class in ReactJS or React Native?

Out of curiosity, I just wanna know what will happen if I use setState() function in constructor of a Class in React Native or ReactJS? Such as:

constructor(props) {   super(props);   this.setState({title: 'new title'}); } 

what's the lifecycle of React gonna happen?


I haven't read the code inside React. I am afraid it will some any damage when I write it that way.

like image 454
Jony Avatar asked Jan 23 '16 09:01

Jony


People also ask

What will happen if you use setState in constructor?

setState" causes React to re-render your application and update the DOM. you can also track of prevstate in setState If you use setState in constructor you would get error like this:Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component.

How do you use setState in constructor in React?

Use the setState() method everywhere else; doing so accepts an object that eventually merges into the component's existing state. For example, the following does not rerender a component: // Wrong this.state.name = 'Obaseki Nosa'; Instead, use setState() .

What happens when you call setState in React native?

The first thing React will do when setState is called is merged the object you passed into setState into the current state of the component. This will kick off a process called reconciliation. The end goal of reconciliation is to, in the most efficient way possible, update the UI based on this new state.

What will happen when you use setState () in componentWillMount ()?

setState() is used to change the name in componentWillMount() and componentDidMount() and the final name is reflected on the screen. An important thing to note here isthat as stated before, componentDidMount() occurs only once to give a render a second pass.


1 Answers

What setState essentially does is to run a bunch of logic you probably don't need in the constructor.

When you go state = {foo : "bar"} you simply assign something to the javascript object state, like you would any other object. (That's all state is by the way, just a regular object local to every component).

When you use setState(), then apart from assigning to the object state react also rerenders the component and all its children. Which you don't need in the constructor, since the component hasn't been rendered anyway.

like image 94
swelet Avatar answered Oct 14 '22 20:10

swelet