Understanding React Constructors with Components: How does constructor work in react?
Updated on Oct 31, 2024 | 8 min read | 13.8k views
Share:
For working professionals
For fresh graduates
More
Updated on Oct 31, 2024 | 8 min read | 13.8k views
Share:
Table of Contents
In our daily lives, we come across many tools that help us complete things a lot faster by taking care of many things under the hood. A simple example we can take is UPCI apps like Paytm, PhonePe, and GooglePay, etc., If we look at them, all of them are individual payment apps, but in the end all these apps will interact with the NPCI-UPI system for us to send and receive money seamlessly.
Just like the NPCI-UPI system, I guess you might have heard of React. React is a popular JavaScript library used extensively in front-end development or web development. It is used by developers for developing user interfaces. Learning React will be very helpful in securing high paying front-end developer or UI developer positions. In this article, we’ll learn about a concept called react constructor in the react component, that will be very helpful and allows us to build components a lot faster. To learn and gain experience in React, enroll in the best React online course provided by upGrad.
In a class, a constructor is a method that is automatically called when an object of that class is created. Typically, this is how it works:
Syntax:
Constructor(props){
super(props);
}
A couple of points to note about a constructor are:
We must remember that the setState() method cannot be used directly in the constructor(). Use 'this.state' to assign the initial state in the constructor. The constructor uses this.state to assign initial state, and other methods should use set.state().
In React, the constructor is called during component creation and before mounting. If you want to implement the constructor for a React component, call the super(props) method before any other statement. Otherwise, this. props will be undefined in the constructor and create bugs.
constructor() {
console.log(this.props);
}
Using super(props) is simple. We just have to call it in the constructor method of our child component:
constructor(props) {
super(props);
console.log(this.props);
}
The constructor is the ideal place to set up your component's initial state. Instead of using setState() in other methods, you will need to assign the initial state directly.
class Hello extends React.Component {
constructor(props) {
super(props);
this.setState({
title: 'This is the first test'
});
}
render() {
return <div>{this.state.title} </div>
}
}
ReactDOM.render(<Hello />, document.getElementById('container'));
When you use the setState() method in React, it does more than just assign a new value to this. state. It also re-renders the component and all its children. Additionally, if you are trying to update a class that was defined inside of a constructor, you will receive an error, so we should avoid setState() in constructors because it is the only place we directly assign the initial state to this.state.
constructor(props) {
super(props);
this.state = {
name 'kapil',
age: 22,
};
}
When creating a component, you should avoid setting values directly from the component's properties. Do it as follows:
constructor(props) {
super(props);
this.state = {
name: props.name,
};
}
If you try to change the name property in the state object, it will not work. If you want to modify this property later, you should not use setState(). Instead, access the name property directly in your code by using this.props. name instead of assigning it directly to the state.
In the constructor, you can bind event handlers easily:
constructor(props) {
super(props);
this.state = {
// Sets that initial state
};
// Our event handlers
this.onClick = this.onClick.bind(this);
this.onKeyUp = this.onKeyUp.bind(this);
// Rest Code
}
It might be tempting to set the component's state right away, but this could cause a few issues. One issue is that you can't really test it properly until the API call has been made and the response received. Another reason to avoid setting state in the constructor is that you don't need to worry about that value again once it's been defined.
While this may seem the obvious approach, the constructor function is not always the right place to do API calls. If your component relies on another state that is available in its parent or grandparent components, then you may want to consider making API calls in componentDidMount(). This way you don't need to make API calls multiple times.
constructor(props) {
super(props);
this.state = {
Reptile: 'Alligator',
};
}
In general, anything that affects other parts of the code that is outside of the scope of a function or expression that is currently being executed is called a side-effect. To be more precise, any function or expression that changes the values of a state or a variable that is outside of the function’s environment is known to be having side-effects.
Actions like fetching data or changing the DOM in a react component constructor directly are a few examples of side effects. Side effects should be avoided because
React component constructor has many advantages that are more useful when we are working on a large-scale React application. Also, it is important to know that constructors are present in class-based components only, functional components do not have constructors. Two of the main purposes of the react constructors are:
Component state initialization is one of the main purposes of the constructor in React Js. The state contains the date needed by the react component to render and keep track of. By using the react component, we can set the initial state that contains the starting point for the component data.
Example
// importing React component
import React from 'react';
// creating class with name MyComponent
class MyComponent extends React.Component {
// constructor method which is receiving props as parameter
constructor(props) {
// calling super class constructor along with props
super(props);
// initializing state with default score value of 0
this.state = {
score: 0
};
}
render() {
return (
<div>
<h1>Score: {this.state.score}</h1>
<button onClick={this.incrementScore}>Increment</button>
</div>
);
}
// incrementScore function responsible for increasing the score by 1
// every time the button is clicked
incrementScore= () => {
this.setState((prevState) => ({
// accessing the previous score and increasing it by 1
score: prevState.score+ 1
}));
}
}
// exports this component as MyComponent
export default MyComponent;
Explanation
The above code is a react constructor example where we are using a constructor to set the initial state of the component.
// importing React component
import React from 'react';
// creating class with name MyComponent
class MyComponent extends React.Component {
// constructor method which is receiving props as parameter
constructor(props) {
// calling super class constructor along with props
super(props);
// initializing state with default score value of 0
this.state = {
score: 0
};
// setting the onButtonClick event handler
this.onButtonClick = this. onButtonClick.bind(this);
}
// renders the content to be displayed
render() {
return (
<div>
<h1> Score: {this.state.score}</h1>
<button onClick={this. onButtonClick}>Increment</button>
</div>
);
}
// function called every time every time the button is clicked
onButtonClick () {
// updated the state with the new value
this.setState((prevState) => ({
// accessing the previous score and increasing it by 1
score: prevState. score + 1
}));
}
}
// exports this component as MyComponent
export default MyComponent;
Explanation
In the above code, we have a constructor method declared at the beginning of the component, which is receiving props as a method parameter.
React components have a useful feature as constructors. Constructors are difficult to manage. Don’t define the constructors if the state in the components would not be maintained. React applications are built using functional components and if state or event handlers are not required then it is better not to have the class components.
Arrow functions make it possible to write more concise code, and they also help you to use the ‘this’ binding correctly. If you're using arrow functions, then you don't need to bind any event to 'this'. The scope of 'this' is global and not limited to any calling function.
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {
data: 'ABC'
}
}
handleEvent = () => {
console.log(this.props);
}
render() {
return (
<div className="App">
<h2>React Constructor Example</h2>
<input type ="text" value={this.state.data} />
<button onClick={this.handleEvent}>Please Click</button>
</div>
);
}
}
export default App;
class App extends Component {
constructor(props){
// here, it is setting initial value for 'inputTextValue'
this.state = {
inputTextValue: 'initial value',
};
}
}
class App extends Component {
constructor(props) {
// when you use 'this' in constructor, super() needs to be called first
super();
// it means, when you want to use 'this.props' in constructor, call it as below
super(props);
}
}
class App extends Component {
constructor(props) {
this.myBook = new MyBookLibrary();
//Here, you can access props without using 'this'
this.Book2 = new MyBookLibrary(props.environment);
}
}
class App extends Component {
constructor(props) {
// when you need to 'bind' context to a function
this.handleFunction = this.handleFunction.bind(this);
}
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
class Main extends React.Component {
constructor() {
super();
this.state = {
planet: "Earth"
}
}
render() {
return (
< h1 >Hello {this.state.planet}!</h1>
);
}
}
ReactDOM.render(<Main />, document.getElementById('root'));
Output:
Hello Earth!
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
class Main extends React.Component {
state = {
planet: "Mars"
}
render() {
return (
< h1 >Hello {this.state.planet}!</h1>
);
}
}
ReactDOM.render(<Main />, document.getElementById('root'));
Output:
Hello Mars!
In a react constructor, the super(props) will let us call the superclass constructor and inherit its properties and will also allow us to pass in additional properties as arguments to the super component. Constructors are present in many popular programming languages, learn more about them and become experienced in front-end development.
To wrap things up, React Constructor components are very helpful. They play an important role and help us in initializing components, and states, and binding event handlers. A better understanding of the React component constructors helps in better creating and managing our React application and components. Learn more about React from the upGrad best React online course.
Enhance your technical prowess with our Software Development Skills programs. Discover the options below to find the right fit.
Strengthen your skills with our free Software Development Courses. Check out the programs below to select your ideal path.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources