Updated March 28, 2023
Definition of React Constructor
React constructor is a predefined function which will be called automatically on initialization of react component, in this function we can define initial data or states to show for the first time, these data could be “loading data” before getting all data to make better UI impacts.
Syntax
See the below two syntaxes. We are calling super here so that we could be able to use this inside constructor. If we do not use super and we will try to use this inside constructor it will throw an error. Constructor in react js is not a mandatory thing to be co
Syntax #1:
With props in super(props): We pass super with props when we wanted to use this.props inside the constructor. Without passing props in the super function of the constructor, it will not work.
constructor(super) {
super(props);
this.state = {
data: 'loading data',
};
}
Syntax #2:
Without props in super(props): Here we are not passing props in super function. In this case, we can not use this. props inside the constructor.
constructor(super) {
super();
this.state = {
data: 'loading data',
};
}
How does Constructor Work in React?
You have seen every component in react js is a class which is extending react core library, and for any class when class object created or initialization happens it will call to react constructor first. Inside the constructor, a super function call is made these calls are made so that “this” attribute we can be used inside the constructor. Inside constructor for every super call it is not important to pass props, we will pass props only if we want to access “this.props”. In a very general team, we can say that react constructor is a default function for a class to execute on object creation of react component class
In the react js lifecycle their many functions, but the constructor is the function that gets executed first, so if we wanted to do any initialization we can do it inside the constructor. Inside react constructor we should not use this.setState() ,it is only for initialisation .
It’s working principle consists few important thinks they are
- Load On Initialisation: Every time when anyone initializing the component it will load all the initial data, here loading means setting the values of the initial state.
- No need to Call Manually: because the constructor is getting called on initialization we need not required to call constructor function in the to react component, it gets called automatically.
Let me explain its working principle with one real-time example, Suppose you are designing a page for all available product listing for the customer, And we know all the product details are fetched from the server, hence till all products will fetch from other server customer need to wait. Here constructor plays an important role, With the help of constructor we can set some basic and static products for the customer on initialization of component .because constructor initialize or called automatically it will set some products for customers instead of showing any blank page to him.
Examples to Implement Constructor in React
Examples to implement constructors in react are given below:
Example #1
In this example we are calling the ChangeOnClick function, on its first call it will set the “cnt” variable as 6 and each click on it will get an increment it’s value by one and the increased value will be visible to us. Here 6 is the value set by the constructor function for the first time and the value will keep changing and render will called on each change of cnt value.
Code:
class ChangeOnClick extends React.Component {
constructor(props) {
super(props);
this.state = { cnt: 6 };
}
cntFunction = () => {
this.setState(
{ cnt: this.state.cnt + 1 }
);
};
render() {
return (
<h1 onClick={ this.cntFunction }>
change count on each click: { this.state.cnt }
</h1>
);
}
}
React.render(
<ChangeOnClick/>,
document.getElementById('changeonclick')
);
HTML Code:
<div id="changeonclick">
</div>
See the below screen of output, here the initial value of the output is 6, and it will keep changing with clicks.
Output:
Example #2
In the below example we are performing constructor operation, here initially we set some value for the constructor and then again we changed it with the help of time. We can explain the below example in the below way.
Inside SampleConstructor
- In this component, we are setting an initial value for the msg which is “Loading” on component SampleConstructor initialization (Object creation of the class)
- A function called componentDidMount will be called after the first rendering of component and then changing the value of msg accordingly.
Inside ConstructorExample,
- In this component we are setting a flag as initialization inside a constructor, if the value for the flag is true it will call to component SampleConstructor else it will print “different component”
Please see the below example with a screen of outputs,
Code:
class SampleConstructor extends React.Component {
//creating a constructor and calling super with props so that we can able
constructor(props) {
//called a super function inside constructor function so that we can be able to use this.props
super(props);
this.state = {
msg: 'Loading'
}
this.cnt = 1;
}
//do something after rendering html
componentDidMount() {
this.timerForData = setInterval(function(){
this.setState({
msg: this.state.msg === 'Loading' ? 'Data is still loading' : 'Data Loaded'
})
this.cnt = this.cnt + 1;
}.bind(this), 1000);
}
//clear the time interval
componentWillUnmount() {
//clear timer
clearInterval(this.timerForData);
}
render() {
//"return the HTMl message after changing state"
return (
<div>{this.state.msg}</div>
)
}
}
class ConstructorExample extends React.Component {
constructor(props) {
super(props);
this.state = {
flag: true
}
}
componentDidMount() {
this.timerForData = setInterval(function(){
this.setState({
flag: !this.state.flag
})
}.bind(this), 10000);
}
render() {
return (
<div>
{this.state.flag ? <SampleConstructor /> : (<div>different component</div>)}
</div>
)
}
}
ReactDOM.render(<ConstructorExample />, document.getElementById('root'))
HTML Code:
//HTMl file to use above react components
<div id="root"></div>
Output:
Output on initialization of component as it was the value set from the constructor of SampleConstructor.
Once the interval is complete it will change the state value of msg to new. On each change of state, render will be called.
This output comes from the second(ConstructorExample) component. In this component it checks for the flag, here we have set the flag value is true on initialization inside the constructor function. And inside this flag value will keep changing
Recommended Articles
This is a guide to React Constructor. Here we discuss the Introduction, syntax, and working of the constructor in react along with different examples and its code implementation. You may also have a look at the following articles to learn more –