DEV Community

Kayut
Kayut

Posted on

2 2

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

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series