JavaScript Class Components: 2024

Deepak Chaudhari
3 min readJun 19, 2024

--

Class components in JavaScript are particularly useful in various contexts, including object-oriented programming (OOP), React development, and scenarios requiring encapsulation and inheritance. Here are detailed explanations and scenarios where class components are beneficial:

Figure 1.0.0

1. Object-Oriented Programming (OOP)

In traditional OOP, classes are fundamental for creating objects that encapsulate data and behavior.

Use Case: Modeling Real-World Entities

Classes help model real-world entities with attributes and methods.

class Car {
constructor(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
}

displayDetails() {
console.log(`Car: ${this.brand} ${this.model}, Year: ${this.year}`);
}
}

const myCar = new Car('Toyota', 'Corolla', 2020);
myCar.displayDetails(); // Car: Toyota Corolla, Year: 2020

2. Inheritance and Code Reusability

Classes allow inheritance, enabling you to create new classes based on existing ones.

Use Case: Extending Functionality

Create a base class and extend its functionality in derived classes.

class Animal {
constructor(name) {
this.name = name;
}

makeSound() {
console.log(`${this.name} makes a sound.`);
}
}

class Dog extends Animal {
makeSound() {
console.log(`${this.name} barks.`);
}
}

const dog = new Dog('Buddy');
dog.makeSound(); // Buddy barks.

3. React Development

In React, class components were traditionally used for creating components with state and lifecycle methods. Although functional components with hooks are more popular now, class components are still in use and important for understanding legacy code.

Use Case: Stateful Components

When you need a component to maintain and manage its own state.

import React, { Component } from 'react';

class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}

increment = () => {
this.setState({ count: this.state.count + 1 });
}

render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}

export default Counter;

4. Encapsulation

Classes provide encapsulation, allowing you to hide internal details and expose only what is necessary.

Use Case: Managing Complexity

Encapsulate complex logic and data within a class to simplify the interface for other parts of the application.

class BankAccount {
#balance; // Private field

constructor(initialBalance) {
this.#balance = initialBalance;
}

deposit(amount) {
this.#balance += amount;
}

withdraw(amount) {
if (amount > this.#balance) {
console.log('Insufficient funds');
} else {
this.#balance -= amount;
}
}

getBalance() {
return this.#balance;
}
}

const account = new BankAccount(1000);
account.deposit(500);
account.withdraw(300);
console.log(account.getBalance()); // 1200
console.log(account.#balance); // SyntaxError: Private field '#balance' must be declared in an enclosing class

5. Static Methods and Properties

Static methods and properties are associated with the class itself rather than any instance.

Use Case: Utility Functions

Define utility functions that operate on the class level.

class MathUtil {
static add(a, b) {
return a + b;
}

static subtract(a, b) {
return a - b;
}
}

console.log(MathUtil.add(5, 3)); // 8
console.log(MathUtil.subtract(5, 3)); // 2

6. Using Classes in Modules

When developing modular applications, classes can be used to structure the code and provide clear interfaces.

Use Case: Modular Design

Create reusable modules with well-defined interfaces.

// mathUtil.js
export class MathUtil {
static add(a, b) {
return a + b;
}

static subtract(a, b) {
return a - b;
}
}

// main.js
import { MathUtil } from './mathUtil.js';

console.log(MathUtil.add(10, 5)); // 15
console.log(MathUtil.subtract(10, 5)); // 5

Summary

Class components are used in JavaScript for various purposes, including:

  • Modeling real-world entities with OOP principles.
  • Enabling inheritance and code reusability.
  • Managing state and lifecycle in React components.
  • Encapsulating data and functionality.
  • Defining static methods and properties.
  • Structuring code in modular applications.

Understanding how and when to use class components is crucial for writing clean, maintainable, and scalable code.

=============================+ Thank You !!!+==============================
Note: Don’t forget to follow and give 50 claps.👏 👏 👏

--

--