Constructor in React.js
Constructor and main purpose of using Constructor:
The constructor for a React component is called before it is mounted.
Purpose of using Constructor:
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.
constructor(props) { super(props); // Don't call this.setState() here! this.state = { loader: false }; this.handleClick = this.handleClick.bind(this); }
Note: 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.
Q:- Is it mandatory to define constructor for React component?
No, it is not mandatory. i.e, If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component.