Constructor | Lifecycle
lets see how to initialize state of a component using constructor
In React realm mounting refers to the loading of components on the DOM. This phase contains a set of methods which get invoked when the component is getting initialized, and loaded on to the DOM.
The methods which get called are as follows:
constructor This is the first method that gets called whenever a component is created. The constructor is called only once in the whole lifecycle of a component. It’s used to set up the initial values of variables and component state.
Usage: Setup the initial state of the component.
If we render the above component as <ContraMusicPlayer/>
it will by default render with volume level at 70 and it will be in the paused state.
In React’s realm the constructor is the only place where this.state
should be used. Every other method should update the state using this.setState()
One of the best use of constructor is to define the initial state of the component, which is very useful for any react application. We can also bind any event that occurs in our component in the constructor like the following.
In above’s example, the event will fire after the user has clicked the button or keyup, blur or any other event and then we need to set up the context to its parent and not the child context, so we are binding this to parent. Let me take one example to simplify this explanation.
Example
Now, if you run this and see in the console, then it says like this. Uncaught TypeError: Cannot read property 'props' of undefined
That means it can not find this as a global pointer or keyword or object to the component, it finds as that function property this, not a component property.
So, we need a solution to that. Make one new file, called app1.jsx in the src folder and put the code like this.
Now, include this file in the main.js.
And in above code, just replace the following line.
with this line
Now, again run, you can see an empty object in the console. So now, this is pointing to the global context of the React component.
Following example will not working because, I have not use app1.jsx. You can use app1.jsx and modify the main.js as I have mentioned earlier.
Then see in the console, you can find empty object, if you got any error, then please check again the code, you might not have imported app1.jsx in the main.js.
So, we can achieve two purposes with the constructor function.
Set the initial state of the component
Point the global context of this keyword.
Arrow Functions
If you are using arrow functions then, you do not need to bind any event to this. In that scenario, this scope is global and not limited to any calling function. So If you are using ES6 syntax, then it is best practice to use Arrow Function
Last updated