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

ReactjsReact Native

Reactjs Problem Overview


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.

Reactjs Solutions


Solution 1 - Reactjs

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.

Solution 2 - Reactjs

Error Message would be Uncaught TypeError: Cannot read property 'VARIABLE_NAME' of null

Please see the following two jsfiddle snippets.

Case 1) Working solution jsfiddle

class Hello extends React.Component {
	constructor(props) {
	  super(props);

      this.state = {
    	name: 'world'
      } 
	}

  render() {
    return <div>{this.state.name} </div>
  }
}

ReactDOM.render(<Hello />, document.getElementById('container'));

Case 2) Not working solution

class Hello extends React.Component {
	constructor(props) {
	  super(props);

  	  this.setState({
    	name: 'hello'
      });
	}

  render() {
    return <div>{this.state.name} </div>
  }
}

ReactDOM.render(<Hello />, document.getElementById('container'));

This happens: -constructor (starts setState) -render (fails - because state has no property 'name' yet) -name is added to state (but too late - it has already rendered)

Conclusion:

My rule of thumb, inside constructor uses this.state = {} directly, other places use this.setState({ });

Solution 3 - Reactjs

Constructor: Constructor is Used to initialize the state.

State : Components that contain local state have a property called "this.state".

SetState: React components have a method available to them called setState Calling "this.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.

Solution 4 - Reactjs

React have not restricted the use of setState in any lifecycle event. React official docs link for state update

It was told that you cannot access state directly outside constructor . So you are free to call setState anywhere .

Technically setState is meant to update the existing state with some new value passed within ,which react react handles in the next update cycle through batch process,so using console.log of state right after setState will give the stale value.

Now lets focus on what if we call setState in the constructor . React will prepare the batched piece of code with the new state passed into the setState and trigger a update .

While react have not stopped you from doing this ,however it knows that doing so might land you up in trouble so leaves a nice message for you

> Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the component.

React proceeds with further loading of component but the update never reflects for this batch.

So conclusion : If you try to do so you might not end up with error ,but you will have to bear the undesirable behavior as these updates will reflect no where even if triggered .

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonyView Question on Stackoverflow
Solution 1 - ReactjssweletView Answer on Stackoverflow
Solution 2 - ReactjsAlan DongView Answer on Stackoverflow
Solution 3 - Reactjss.kataView Answer on Stackoverflow
Solution 4 - ReactjsDebasish JenaView Answer on Stackoverflow