9

I've seen some react developers define state without a constructor. I like the fact that is simplifies the code, but is it safe to do so?

class Dog extends React.Component {
   state = { sound: 'Woof' }
   return (
      <p>Dog says { this.state.sound }</p>
   )
}

I apologize in advance for the over simplified example.

camloken
  • 131
  • 1
  • 6
  • where have you seen that? do you have an source example? It paid my attention, I'm curious. Thanks. – Facundo La Rocca Apr 21 '17 at 15:29
  • 5
    http://stackoverflow.com/questions/37788342/is-it-better-to-define-state-in-constructor-or-using-property-initializers Possible duplicate. – Abhilash Apr 21 '17 at 15:30
  • There is an example at the bottom of this page: https://www.fullstackreact.com/30-days-of-react/day-11/ – camloken Apr 21 '17 at 16:31
  • Well, why not if Babel allows us to do that? It is a part of es6 as far as I know, but I don't have an actual link on that. In fact either using a constructor for the case or just define sate or whatever like in the topic if you take a look at the result of babel transpile stuff there will be the same thing there for both. Some further reading in this article https://hackernoon.com/the-constructor-is-dead-long-live-the-constructor-c10871bea599 – Igor Chernega Mar 20 '19 at 08:17

1 Answers1

7

Its exactly the same thing. Take a look at the javascript that babel transpiles the code into. There is no difference.

Shaun Sweet
  • 669
  • 5
  • 9