Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 404
Mauj Mishra Avatar asked Nov 23 '25 22:11

Mauj Mishra


1 Answers

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'
 }
like image 90
akhtarvahid Avatar answered Nov 25 '25 10:11

akhtarvahid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!