Introduction:
In today’s world, the topmost used trending JavaScript library is ReactJS, which is used for building dynamic, interactive, and fast web-page applications. Firstly, it was introduced by Facebook but is now managed by Meta.
React.js is on top as it uses the component-based architecture, virtual DOM, cross-platform, Strong Ecosystem, etc. In React, class components allow you to manage state and lifecycle methods. If you are learning React, you will be aware about class components and functional components. Class components used only the constructor() method and other lifecycle methods.
In this article, we will discuss the React constructor in class components with practical examples for beginners to professional levels.
Constructor in React:
The constructor() method is a special function in JavaScript classes that React uses when creating a new component. It is a part of the React lifecycle methods in the class component. With the use of this method, you can easily initialize a new object. When the object is created, the constructor runs automatically.
Here are some key points that are shown below:
• This method helps to initialize the objects, such as state.
• It helps to manage the event handlers to ensure the use of the correct method.
• It runs automatically when the component has rendered.
• With the use of this method, you can pass the parameters as props.
• This is executed first as it passes the parameters to the super method.
Syntax:
class Greeting extends React.Component {
constructor(properties) {
super(properties);
// Initialize your code here
}
render() {
return <div>Welcome, Developers!</div>;
}
}
export default Greeting;
Example
Code:
import React from "react";
class WelcomeBox extends React.Component {
constructor(properties) {
super(properties);
this.state = {
user: properties.username,
age: properties.age
};
this.changeUser = this.changeUser.bind(this);
}
changeUser() {
this.setState({
user: "Guest",
age: this.state.age + 1
});
}
render() {
return (
<div>
<h2>Hello, {this.state.user}!</h2>
<p>Age: {this.state.age}</p>
<button onClick={this.changeUser}>Change User</button>
</div>
);
}
}
export default WelcomeBox;
Why use the Constructor in React?
In React class components, the constructor() method is used during the initialization phase of a component. It helps prepare the component before it is mounted on the DOM.
The constructor plays the most important role in the class components that is shown below in detail:
1) Binding the Event Handlers:
Constructors help to bind the event handler methods in the component instance. You can add the JavaScript function through the handlers’ function, like key or click press, etc.
Syntax:
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
keyClick() {
console.log('Executed your code here');
}
2) Initialize the State:
It helps to set up the initial value of the component state. But you can set the value through the hooks or constructors.
Syntax:
constructor(props) {
super(props);
this.state = { data: 0, name: "User123" };
}
3) Managing the Props in State:
You can pass the props from the parent to initialize state with the use of the super() method.
Syntax:
constructor(props) {
super(props);
this.state = { name: props.data };
}
Constructor with lifecycle methods in React:
Constructor is a part of the Mounting phase of React lifecycle methods. It follows this sequence, which are shown below:
• constructor()
• render()
• componentDidMount()
Example
Code:
import React from "react";
class UserProfile extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "User123",
age: 15
};
console.log("Constructor: State initialized");
}
componentDidMount() {
console.log("componentDidMount: Component mounted");
setTimeout(() => {
this.setState({
name: "Tpoint Tech",
age: 22
});
console.log("componentDidMount: State updated after fetch");
}, 2000);
}
render() {
console.log("Render: Component rendering");
return (
<div>
<h2>User Profile</h2>
<p>Name: {this.state.name}</p>
<p>Age: {this.state.age}</p>
</div>
);
}
}
export default UserProfile;
Output:
User Profile
Name: Tpoint Tech
Age: 22
Constructors with Hooks:
Some of the developers use the functional components instead of the class components.
Example
Code:
import React, { useState, useEffect } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setSeconds((prev) => prev + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
return <h2>Seconds: {seconds}</h2>;
}
export default Timer;
Advantages of Constructors in React
Constructor offers several advantages that are as follows:
• It is helpful in the binding methods.
• This provides a correct way to manage the state.
• Useful for sending the data through the props.
• The constructor is automatically executed when the object is created.
Disadvantages of Constructors in React:
Some of the disadvantages are shown below:
• This uses more boilerplate code, such as super(), constructor() method etc.
• It cannot use any functional components with hooks.
• This cannot use the high-standard ways to manage the application.
Best Practices of Using a Constructor in React
Here are the best practices for using a constructor in React (class components):
- Initialize the state in the constructor(): With the use of this.state = { } method, you can manage the constructor.
- Use Arrow functions: If you are not using the binding methods, you can use the arrow function for better performance and readability.
- Eliminate redundancy: React mainly handles code optimization to avoid re-rendering or make your code more reusable.
- Call using the super(props): If you are using the constructor in the code, first call the super(props) method before using the constructor.
Conclusion
The constructor in React class components plays an important role during the initialization phase. It is mainly used to set the initial state and bind event handlers before the component renders. Additionally, it's used in many ways, like components in files, class components with the use of props.
I recommend that you learn ReactJS from the Tpoint tech website, as it provides React.js tutorials, interview questions, and all its related topics of React.js.