-1

I have a code written by someone else where the constructor where I havestate initialized but also called the setState if props is undefined, the code is as below:

constructor(props) {
    super(props);
    this.state = {
        subId: props.match.params.subId
    }
   if(props!==undefined){
        this.setState({
            subId: props.match.params.subId 
        });
    }
} 

When I execute my module I get the warning in console as warning.js:35 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.

I googled about it and found that the setState should not be called in constructor. But still cannot understand the thing done here in constructor and the ideal way expected by react. Need some help in understanding, whether the code done in constructor is correct, if yes, why, if no, why?

OM The Eternity
  • 15,694
  • 44
  • 120
  • 182

3 Answers3

3

Adding to already given answers I would like to note that setState is an async operation.

Any constructor in javascript by its nature is synchronous function that must construct and "return" instance of the class being constructed. Calling setState in constructor leaves you in undetermined state where you/react cannot rely upon the fact that component construction has been finished.

Amid
  • 21,508
  • 5
  • 57
  • 54
  • use this.state = {//...your state}, calling setState is changing the state before it is even set and before even component is mounted, this will go against the life cycle of react component – Anshul Sahni Aug 17 '17 at 13:11
2

The reason setState exists is because component's state is immutable, and changes to it lead to re-render the component. In the constructor, just change the state directly on this.state.

Also, you don't need to check if the props is undefined, react make sure it's an object for you, and when it's undefined, something seriously wrong happened anyway.

Tr1et
  • 873
  • 11
  • 25
1

Besides setting the state with setState it also has the mechanism of re-rendering on change. The constructor is executed before it is actually mounted and will not render something. That's why it makes no sense to use setState in the constructor.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107