The original title of this blog post was "What does constructor actually do?" But as I struggled to get my thoughts down to 1 min or less, my dismal attempt at creating a poems app helped to crystalize the question I wanted to address.
If it's a question of what the constructor does, the answer is :
- to initialize your component
But why someone might use constructor versus initializing state ={}
is less clear. Though I've researched the topic, I'm still grasping at the nuanced differences for when is the best time to choose one over the other
I personally like using class components without props because:
- it's simpler/shorter code
- it inherits methods from React.Component
- Also inherits constructor, which you won't have to write (though you can still choose to)
Creating Component without props
class MyComponent extends Component {
state = {
}
...
Surprisingly, many online resources use functional components or use class with props. This means you have to:
- write more lines of code
- create a constructor with props
- then pass the props value from constructor to super
- call
super(props)
in order to can usethis.props
Creating Component with props
class MyComponent extends React.Component {
constructor() {
super();
this.state={
}
}
...
Clearly, I need to read more on this topic. But since it's something I am having to spend more time on, it seemed like it might be helpful to share what I've learned.
As always, here's a StackOverflow link I came across in my Googling
Top comments (0)