DEV Community

Kayut
Kayut

Posted on

Class definition in React

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?

Discussion (3)

Collapse
10secondsofcode profile image
Elango Sundar

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

Collapse
kozakrisz profile image
Krisztian Kecskes
Collapse
dance2die profile image
Sung M. Kim

πŸ‘† 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() { ...  }
}