Why this.setState() is not working in the constructor?

Viewed 624

I was working with react.js and I added this.setState() in the constructor but it doesnt work. Here is my code -

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      age: '18'
    }
    this.setState({id: 'name'}); 
  }
  render(){
    return (
      <div>
        <p>{this.state.id}</p>
        <p>{this.state.value}</p>
      </div>
    )
  }
}

This renders the second p tag but not the first why so?

3 Answers

The setState function, besides setting the state it also has the mechanism of re-rendering on change.

The constructor is executed before the component is actually mounted and will not render something. That's why it makes no sense to use setState in the constructor.

so you will need to achieve this like so:

constructor(props) {
    super(props);

    this.state = {
      age: '18',
      id: 'name'
    }
  }

Don't use setState() inside constructor or inside render method

constructor- is called once when the instance is created if you create inside constructor rerendering won't happen.

render - if you use setState() inside the render method it will go to infinite because re-rendering happens when you use setState()

if you want to save such property to state do it inside lifecycle method componentDidMount()

Improved

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      age: '18'
    }
  }
  componentDidMount(){
    this.setState({id: 'name'}); 
  }
  render(){
    return (
      <div>
        <p>{this.state.id}</p>
        <p>{this.state.value}</p>
      </div>
    )
  }
}

or directly put as you did for age

 this.state = {
      age: '18',
      id: 'name'
 }
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      age: '18',
      id: '',
    }
  }
​
componentDidMount(){
 this.setState({id: 'name'}); 
}
​
  render(){
    return (
      <div>
        <p>{this.state.id}</p>
        <p>{this.state.age}</p>
      </div>
    )
  }
}
Related