🔹 1. Functional Components (Modern Way)
- A JavaScript function that returns JSX.
- Can use Hooks (
useState,useEffect, etc.) to manage state & lifecycle. - Easier to read, test, and maintain.
- No need to use
thiskeyword.
✅ Example:
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
🔹 2. Class Components (Older Way)
- ES6 class extending
React.Component. - Use
this.statefor state management. - Use lifecycle methods (
componentDidMount,componentDidUpdate, etc.). - More boilerplate code compared to functional components.
✅ 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 (
<div>
<h2>Count: {this.state.count}</h2>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default Counter;
🔹 3. Key Differences Between Functional vs Class Components
| Feature | Functional Component ✅ | Class Component 🏛️ |
|---|---|---|
| Syntax | Simple function | ES6 Class |
| State | Managed via Hooks (useState) |
Managed via this.state |
| Lifecycle | useEffect, useLayoutEffect, etc. |
Lifecycle methods (componentDidMount, etc.) |
this keyword |
❌ Not used | ✅ Used everywhere |
| Performance | Generally faster (less boilerplate) | Slightly heavier |
| Code Size | Short & clean | Verbose & more code |
| Best Practice | Modern React | Legacy support |
🔹 4. Why We Use Functional Components Over Class Components?
✅ Advantages of Functional Components:
- Cleaner & concise syntax → easy to read and test.
- Hooks make them powerful → can handle state, side effects, refs, context, etc.
- No confusion with
thiskeyword. - Better performance optimizations (React can optimize function components better).
- Easier for new developers to learn (just functions).
- React team recommends functional components → class components are now considered legacy.
✅ Short Interview Answer
“Functional components are simpler, faster, and use Hooks for state & lifecycle management, making them more powerful than class components. Class components are older, rely on
this, and have more boilerplate. In modern React, functional components are preferred because they’re concise, easier to maintain, and future-proof.”