Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it appropriate to use a constructor in REACT?

I understand the concept of constructors in OOP languages like C++. However, I am not entirely sure when to use a constructor in REACT. I do understand that JavaScript is object oriented, but I am not sure what the constructor is actually 'constructing'.

When rendering a child component, do you need a constructor in the child component? For example:

class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         items: [],
         error: null
      }
    }
    render () {
       return (
          <React.Fragment>
             <ChildComponent data={this.state.items}></ChildComponent>
          </React.Fragment>
       )
    }
}

I will keep the example short for the sake of brevity. But, why would do you need a constructor? And would you need a constructor in the child component for props?

It is possible that my ES6 knowledge is not up to snuff.

like image 454
WebDream Avatar asked Oct 27 '18 13:10

WebDream


2 Answers

A constructor function is NOT required at all.

State initialization can be done directly in the body of a class and function can be assigned to properties as described below,

Technically these are known as class properties, it may land up soon in native javascript, yet because almost all of us use Babel transpiler for React projects, we can use that syntax

class Comp extends React.Component {
/* 
 * generally we do not need to put the props in state, but even if we need to.
 * then it is accessible in this.props as shown below 
**/
state={ first: 1, second: this.props.second } 

handler= (token) => {
 this.setState(prevState => ({first: prevState.first+1}));
}

render() {
 return <div onClick={this.handler}>{this.state.first} and {this.state.second } </div>
}
}

Read more details about class properties and removing constructor from react class component over here. https://hackernoon.com/the-constructor-is-dead-long-live-the-constructor-c10871bea599

like image 52
Akshay Vijay Jain Avatar answered Oct 02 '22 21:10

Akshay Vijay Jain


If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.

The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

Typically, in React constructors are only used for two purposes:

  • Initializing local state by assigning an object to this.state.
  • Binding event handler methods to an instance.

https://reactjs.org/docs/react-component.html#constructor

like image 22
wang Avatar answered Oct 02 '22 22:10

wang