Course contentsShow
← React
Lesson 290 of 2,3969. Class Components (Legacy Overview)Free lesson

constructor() and super(props)

Learn the constructor pattern for initializing state, and why super(props) was required before accessing this.

constructor() and super(props)

You'll learn why class components need a constructor and what super(props) actually does before you can use this.

The Constructor Setup

When you create a class component that needs to initialize state or bind methods, you write a constructor(). This special method runs once when the component is first created.

class Greeting extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    return <h1>Count: {this.state.count}</h1>;
  }
}

Why super(props)?

The super(props) line calls the parent class's constructor (React.Component). Think of it like getting your inheritance before you can spend it—you must call super() before you can access this in your constructor.

Why pass props? Passing props to super() ensures that this.props is properly set up inside the constructor. Without it, this.props would be undefined during construction (though React sets it later for render()).

constructor(props) {
  // super(props);  // ❌ Commented out
  console.log(this.props); // undefined!
}
constructor(props) {
  super(props);  // ✅ Correct
  console.log(this.props); // Works!
}

The Rule

Always call super(props) as the first line in your constructor. It's required by JavaScript's class inheritance rules, and React expects props passed along.

Key Takeaway: constructor() initializes your component's state, and super(props) must be called first to properly set up this and this.props from the parent React.Component class.