Skip to main content
InterviewHubPRO
Section Overview
Q379

Question 379 of 407

Part 9: React Hooks Deep Dive (262 - 316)

93%
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:

  1. Initializing Local State: Assigning an object directly to this.state (without calling setState).
  2. Binding Event Handler Methods: Binding instance methods to this (e.g. this.handleClick = this.handleClick.bind(this)) so this is 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>;
  }
}