For enquiries call:

Phone

+1-469-442-0620

Easter Sale-mobile

HomeBlogWeb DevelopmentUnderstanding React Component Constructor

Understanding React Component Constructor

Published
29th Jan, 2024
Views
view count loader
Read it in
8 Mins
In this article
    Understanding React Component Constructor

    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 KnowledgeHut.

    What is a Constructor?

    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:

    1. It is not necessary to have a constructor in every component.
    2. It is necessary to call super() within the constructor. To set property or use 'this' inside the constructor it is mandatory to call super().

    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().

    Call super(props) Before Using this.props

    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);
    }

    Never Call setState() Inside constructor()

    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.

    Bind Events All in One Place

    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 
    }

    Avoid Assigning Values from this.props to this.state

    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', 
      }; 
    }

    Avoid using side effects in react constructors

    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

    • In most cases, side effects are meaningless, and sometimes, the code in side-effects may not even run at all, like in the case of Server-Side Rendering.
    • Sometimes, the code in a constructor in a react component may trigger the state to update by triggering setState, which is not required.
    • Sometimes, code in the react constructor may re-initialize the component, thus resulting in making unwanted API calls to the backend.
    • Code in the constructor in the react component may take a lot of time to render the component even if the API call had finished a long back.

    What is the purpose of a constructor in a React component?

    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:

    • Initializing component state
    • Binding event handlers 

    Initializing component state

    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.

    • In the above code, we have a constructor method declared at the beginning of the react component, which is receiving props as a method parameter.
    • Inside of the constructor method, we are calling the superclass constructor by passing the constructor props with the code line super(props). React.component is the superclass here and the component MyComponent is the child component.
    • After the super(props) call, we are setting the initial state with only one score property, and its default value is set to 0.
    • After the react component constructor method, we have the render method which will render the JSX of this component.
    • At the end, we have the incrementScore method, which is called every time the button with the text Increment is clicked. This method will increase the score value by one every time the function is called.

    Binding Event Handlers

    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
        };
    // 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.
    • Inside the constructor method, super(props) is called first, which passes props as an argument to the constructor of the parent class, which is React.Component.
    • After the super(props) call, we are initializing the state with only 1 property which is the score, and it is having an initial value of 0.
    • After the state object, we have a line where we bind the method onButtonClick to the component. Usually, when a method is called, the value of this keyword depends on how and where the function is called. To have the correct component instance context, when we try to use this keyword, binding in this way, is needed.  
    • After the constructor method, we have render method which will render the JSX of this component.
    • At the end, we have a method called onButtonClick, which is used to increase the score value by 1 every time this method is called. This method is called every time the button with the text Increment is clicked.

    Do You Even Need a Constructor?

    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

    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. Not sure how to begin your journey in web development? Check out online Course Web Development.   

    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;

    The use of a constructor

    1) Initialization of the state constructor

    class App extends Component {   
      constructor(props){   
            // here, it is setting initial value for 'inputTextValue'   
            this.state = {   
                inputTextValue: 'initial value',   
            };   
      }   
    }

    2) The way to use 'this' inside the constructor

    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);   
        }   
    }

    3) Initialization of third-party libraries

    class App extends Component {   
        constructor(props) {  
            this.myBook = new MyBookLibrary(); 
            //Here, you can access props without using 'this'   
            this.Book2 = new MyBookLibrary(props.environment);   
        }   
    }

    4) Binding some context(this) when we need a class method to be passed in props to children.

    class App extends Component { 
        constructor(props) {   
            // when you need to 'bind' context to a function   
            this.handleFunction = this.handleFunction.bind(this);   
        }   
    }

    Example Program:

    React Component with Constructor

    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! 

    React Component without Constructor 

    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! 

    What is the role of super(props) in the constructor? 

    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 from the best course for Web Development. 

    React Constructor: Best Practices to Use 

    • Avoid code duplication:
      • If you have more than one component in your React application, then make sure to call the super class constructor with super(props) before anything else in your component’s constructor. 
    • Avoid setting values from props to state 
      • Setting values from properties (props) to a state in a React component will make it hard to set state later using setState. Instead of it, try to set the properties directly, by using this.props. 
    • Avoid using side effects in a constructor  
    • Do not use setState inside of a constructor 
      • You need to set the state directly in a constructor by using this.state object. 
    • Keep all your event bindings in one place 
      • You can add all your event handlers' bindings in one place inside a React constructor. This will help in keeping track of all the bindings and will be very helpful when the project increases in depth. 

    Wrap-up

    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 KnowledgeHut best React online course.

    Frequently Asked Questions (FAQs)

    1Can a React component have a constructor without calling super(props)?

    Yes, a React component can have a constructor without calling the super(props).

    2When should I use a constructor in a React component?

    Because of the advantages of a constructor in a react component, it is a best practice to always try to use one. 

    3Are there alternatives to using a constructor in React components?

    There are a few alternatives to using a constructor in a React component, which are: 

    • Class Properties 
    • Functional Components 
    • ES6 Class Methods

    But it is always a better practice to use a constructor in a React component. 

    Profile

    Rajesh Bhagia

    Blog Author

    Rajesh Bhagia is experienced campaigner in Lamp technologies and has 10 years of experience in Project Management. He has worked in Multinational companies and has handled small to very complex projects single-handedly. He started his career as Junior Programmer and has evolved in different positions including Project Manager of Projects in E-commerce Portals. Currently, he is handling one of the largest project in E-commerce Domain in MNC company which deals in nearly 9.5 million SKU's.

    In his role as Project Manager at MNC company, Rajesh fosters an environment of teamwork and ensures that strategy is clearly defined while overseeing performance and maintaining morale. His strong communication and client service skills enhance his process-driven management philosophy.

    Rajesh is a certified Zend Professional and has developed a flair for implementing PMP Knowledge Areas in daily work schedules. He has well understood the importance of these process and considers that using the knowledge Areas efficiently and correctly can turn projects to success. He also writes articles/blogs on Technology and Management

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon