React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)
What is the main purpose of constructor?
junior LevelCode ExampleHooks
In React class components, the constructor is mainly used for two purposes:
- Initializing Local State: Assigning an object directly to
this.state(without callingsetState). - Binding Event Handler Methods: Binding instance methods to
this(e.g.this.handleClick = this.handleClick.bind(this)) sothisis preserved when passed as callbacks.
Code Example
jsx
import React, { Component } from 'react';
class UserCard extends Component {
constructor(props) {
super(props); // Required to access this.props inside constructor
// 1. Initializing local state
this.state = { isOnline: false };
// 2. Binding event handler method
this.toggleStatus = this.toggleStatus.bind(this);
}
toggleStatus() {
this.setState((prev) => ({ isOnline: !prev.isOnline }));
}
render() {
return <button onClick={this.toggleStatus}>{this.state.isOnline ? 'Online' : 'Offline'}</button>;
}
}