If you are coming from languages like Java or maybe C++, then you would be familiar with classes and OOP concepts. To make JavaScript more approachable for developers with such backgrounds, ‘class’ was introduced in ES6. A class in JavaScript is essentially syntactic sugar on top of constructor functions or prototypes, which is how classes were previously created in JavaScript. If all of this sounds unfamiliar, let me explain with an example.
Imagine you wanted to create a bunch of objects, and each object must have properties like name, email, roll number, and a method (function) that lets students give attendance. Would you create the following object 100 times for all the students with the same properties and methods? No, right? Remember the DRY (Don’t Repeat Yourself) principle?
Object creation in JavaScript
To avoid writing the same code 100 times, you can create a class that will serve as a blueprint for all future objects.
Class creation in JavaScript
Now imagine there is a class monitor who has the same properties and methods as students, but in addition, this person has the function to mark someone absent.
Inheritance in JavaScript
This is called inheritance, where Monitor inherits the properties of Student but also has its own method, markAbsent. In this case, JavaScript automatically calls the constructor function of the parent class and passes the values from Monitor to the Student class to create an instance, then adds its own method, markAbsent. But behind the scenes it is doing the below to achieve this.
In React, when you create a class-based component, you extend the predefined class React.Component and write constructor(props) and super(props) to properly initialize this.props and this.state in the component. This is especially important for dealing with the component’s lifecycle and rendering.
Class based component in React
By calling super(props), you ensure that the parent class (React.Component) performs its necessary initializations, allowing your component to function correctly within the React framework. This is crucial for accessing this.props and setting up the component’s initial state based on the props.