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 ob
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 {this.state.first} and {this.state.second }
}
}
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