Sunday, August 12, 2018

React Component Lifecycle - Constructor

The constructor is the first life-cycle method invoked when a React component is mounting / initializing. The following code snippet shows a basic constructor for a React component with state initialization and event binding.

constructor(props) {
 super(props);
 this.state = {};
 this.handleClick = this.handleClick.bind(this); 
}

The super() method in constructor initialized "this", hence super() should be the first statement in the constructor() and "this" should not be used before calling super(). Constructor is not required for components which don't have state and events, however if there is a constructor() the super() method must be there in the constructor().

The props parameter in super(props) is required when we want to use the props passed to the component in the Constructor. Call super(props) only if you want to access this.props inside the constructor. React automatically set it for you if you want to access it anywhere else.

The constructor serves two purposes.
It is used to initialize state of the component.
It is used to bind the event handlers used in the Component.

Initialize State
The state of the component is initialized using this.state
this.state = {};

The constructor is the only place where we can set the state using this.state, to change the state in any other life-cycle methods we should use this.setState()

Bind Event handlers
Event required for the controls in the component are bound to their handlers using bind()
this.handleClick = this.handleClick.bind(this);

We can bind events to handlers in the render() method also like this
onClick={this.handleClick.bind(this)}

This approach works fine, however in this approach the binding function is re-allocated whenever render() is called. We know that render() gets called whenever thre is a change in the components state or props, hence this approach is not recommended for performance reasons. To avoid this we bind the event handlers in the constructor.

Search Flipkart Products:
Flipkart.com

No comments: