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?

Top comments (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() { ...  }
}

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠