0

all just want to know the difference b/w the following ways to initialize the state and is there any advantage or disadvantage over using another one, or both are just syntactic sugar.

i)

constructor(props) {
    super(props)
    this.state = { bar: 0 }
  }
  render() {
    return <div>Foo</div>
  }
}

ii)

class Foo extends React.Component {  
  state = { bar: 0 }

  render() {
    return <div>Foo</div>
  }
}

Did anyone have any idea and what method i should prefer in which situation

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Night owl
  • 145
  • 10
  • 1
    I believe your second example is not complete – MorKadosh Sep 14 '21 at 05:29
  • 1
    In the first example you can initialize the state using props, while on the second you can't. – MorKadosh Sep 14 '21 at 05:32
  • @MorKadosh No, the second example is a complete class component. Very minimal, but complete and valid. – Drew Reese Sep 14 '21 at 05:37
  • @DrewReese OP didn't format properly. So few lines were hidden. – Ramesh Reddy Sep 14 '21 at 05:38
  • @RameshReddy Ah, I see, then I probably would have just left it at that with the comment instead of also editing in syntactically correct and complete code. You never know if they have a typo in their code. – Drew Reese Sep 14 '21 at 05:41
  • @MorKadosh are you sure about that? I'm pretty sure `this.props` will work in the second case as well. Although it has been a while since I've used or even seen a class components, so do correct me if i'm wrong. – nullptr Sep 14 '21 at 05:44
  • 2
    Does this answer your question? [this.state vs state in React](https://stackoverflow.com/questions/51118103/this-state-vs-state-in-react) – PRSHL Sep 14 '21 at 05:44

0 Answers0