Difference Between Functional and Class Components in React
What Are Components in React?
Components are building blocks of React application. They can be:
- Functional — regular JavaScript functions
- Class-based — classes inheriting
React.Component
Main Differences
| Functional components | Class components | |
|---|---|---|
| Syntax | function MyComponent() | class MyComponent extends React.Component |
| State support | Yes (via useState, useReducer) | Yes (via this.state) |
| Lifecycle | Through hooks (useEffect) | Methods (componentDidMount, etc.) |
| Context | useContext() | this.context |
| this | No this | Uses this |
| Code brevity | shorter and simpler | more verbose |
| Hooks support | Yes | No |
| Performance (theoretically) | Slightly higher | Slightly lower |
Functional Component Example
import { useState, useEffect } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Component rendered");
return () => {
console.log("Component unmounted");
};
}, []);
return (
<div>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
);
}
Class Component Example
import React from "react";
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
console.log("Component rendered");
}
componentWillUnmount() {
console.log("Component unmounted");
}
render() {
return (
<div>
<p>Counter: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
+
</button>
</div>
);
}
}
When to Use
- Functional components — modern standard. Used in 99% of cases, especially with hooks.
- Class components — in legacy projects or when working with legacy code.
Conclusion
- Functional components are simpler and more convenient, especially with hooks appearance.
- Class components are considered outdated and used only for backward compatibility.
- All new projects are recommended to be written only using functional components.