Class definition in React

github logo ・1 min read

Does a Class component in React need to have a constructor like the following example:

class App extends React.Component {
    constructor() {
        super()
        this.state = {
            count: 0
        }
    }
render() {
  ...
}
}

Or now we can define a Class component without using a constructor, like the following example?:

class App extends React.Component {
        this.state = {
            count: 0
        }
render() {
  ...
}
}

Which one is correct?
Do we still need to write the constructor for a Class component?

twitter logo DISCUSS (3)
markdown guide
 

@kayut If you don't have child class means, you can use as second option like without constructor.

 
 

👆 answers the question 👍

@kayut
And note that the state is initialized as a property outside of constructor, this. should be dropped.

class App extends React.Component {
  // not this.state but just state
  state = {
    count: 0
  };
  render() { ...  }
}
Classic DEV Post from Jun 23

Being a Female Programmer: How is it For You?

This probably depends on where we live and work, but personally, I have not experienced anything negative for being a female programmer in my few years of career.

Kayut profile image

A blogging community of over 100,000 software developers Join dev.to