0

whats the difference between the following two code i.e,( states in constructor or not) how it works. when do we use one over the other?

 class abc extends React.Component {
constructor(props) {
    super(props);
    this.state = {value: 0};
} 
}

Here if I don't specify this though it works

  class abc extends React.Component {
  state = {
    value: 0,
  };
  }

I'm lil confused can anyone explain please

anonomous
  • 27
  • 7
  • @CertainPerformance its in class and not function. – anonomous Dec 10 '18 at 07:53
  • @CertainPerformance I've updated my code – anonomous Dec 10 '18 at 08:03
  • Possible duplicate of [What is the difference between using constructor vs state = {} to declare state in react component?](https://stackoverflow.com/questions/45451141/what-is-the-difference-between-using-constructor-vs-state-to-declare-state) – JJJ Dec 10 '18 at 08:07

2 Answers2

0

This the other way to initialize state . Actually, Babel will transpile your code and add a constructor for you behind the scenes. Please check this article for more details: https://maksimivanov.com/posts/react-state/

Umair Farooq
  • 1,763
  • 13
  • 16
0

Another distinction other than the one Umair Farooq pointed out, is that if you are using your component as child and you need to pass props, then your first option is needed. A top level/parent component may omit the contructor/super option.

KT-mongo
  • 2,044
  • 4
  • 18
  • 28
  • then what is the use of constructor and super when without it too the this.state works – anonomous Dec 10 '18 at 14:02
  • The job of the constructor and super is not how you display this.state or state. Their main purpose in react terms at least is to receive props from the parent. So if you don't use class based component that receives props you don't have to use constructor and super – KT-mongo Dec 10 '18 at 22:01