React JS

Difference between class component and functional component which one do you use and why ?

I prefer Functional Components because they are simpler, support React Hooks, require less code, and are the recommended approach in modern React and Next.js applications. I use Class Components only when working on legacy projects that were built before Hooks were introduced.

Class Component vs Functional Component

FeatureClass ComponentFunctional Component
SyntaxUses ES6 classUses JavaScript function
State Managementthis.stateuseState() Hook
Lifecycle MethodscomponentDidMount(), componentDidUpdate(), etc.useEffect() Hook
this KeywordRequiredNot required
Code SizeMore boilerplateLess code
ReadabilityMore complexEasier to read
PerformanceSlightly heavierGenerally lighter
Hooks SupportNoYes
Modern ReactRarely usedRecommended

Class Component Example

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 (
<>
<h2>{this.state.count}</h2>
<button onClick={this.increment}>Increment</button>
</>
);
}
}

export default Counter;

Functional Component Example

import { useState } from "react";

function Counter() {
const [count, setCount] = useState(0);

const increment = () => {
setCount(count + 1);
};

return (
<>
<h2>{count}</h2>
<button onClick={increment}>Increment</button>
</>
);
}

export default Counter;

Lifecycle Methods

Class Component

componentDidMount() {
console.log("Page Loaded");
}

componentWillUnmount() {
console.log("Component Removed");
}

Functional Component

useEffect(() => {
console.log("Page Loaded");

return () => {
console.log("Component Removed");
};
}, []);

Which One Do You Use?

Answer for Interview

I use Functional Components in all new React and Next.js projects because they are simpler, require less code, support Hooks like useState, useEffect, useMemo, and useCallback, and are the recommended approach by React. Class Components are mainly used when maintaining older legacy applications.


Why Functional Components?

1. Less Boilerplate

Class:

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

Functional:

const [data, setData] = useState([]);

2. Hooks

const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(false);

useEffect(() => {
fetchUsers();
}, []);

3. Better Reusability

Custom Hook:

function useCounter() {
const [count, setCount] = useState(0);

const increment = () => setCount(count + 1);

return { count, increment };
}

4. Preferred in Next.js

In modern Next.js (App Router), almost all components are Functional Components:

export default function JobsPage() {
return (
<div>
<h1>Jobs</h1>
</div>
);
}

Class Components are rarely used in Next.js applications.