Components in React: Functional vs. Class Components
Source: Dev.to
What are React Components?
React components are reusable building blocks for UI. They allow you to break down a UI into smaller, independent pieces.
Types of Components in React
React has two types of components:
- Functional Components (modern, recommended)
- Class Components (older)
1. Functional Components (Recommended)
Functional components are JavaScript functions that return JSX.
function Greeting() {
return <h1>Hello, React!</h1>;
}
export default Greeting;
Why Use Functional Components?
- Simpler and easier to read
- No need for the
thiskeyword - Hooks (
useState,useEffect, etc.) work only in functional components
2. Class Components (Older Method)
Class components use ES6 classes and a render() method to return JSX.
import React, { Component } from "react";
class Greeting extends Component {
render() {
return <h1>Hello, React!</h1>;
}
}
export default Greeting;
Why Avoid Class Components?
- More complex syntax
- The
thiskeyword can be confusing - Hooks like
useStatecannot be used directly
State in Components
✅ State in Functional Components (Using useState)
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
export default Counter;
❌ State in Class Components (Using this.state)
import React, { Component } from "react";
class Counter extends Component {
constructor() {
super();
this.state = { count: 0 };
}
increaseCount = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increaseCount}>Increase</button>
</div>
);
}
}
export default Counter;
Functional components with hooks (useState) are shorter and cleaner.
Props in Components
✅ Using Props in Functional Components
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Usage
// <Welcome name="Alice" />
❌ Using Props in Class Components
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
// Usage
// <Welcome name="Alice" />
Functional vs. Class Components: Comparison
| Feature | Functional Components | Class Components |
|---|---|---|
| Syntax Simplicity | Simple & clean | More complex |
| Performance | Faster | Slightly slower |
this Keyword | Not required | Required |
| State Management | useState hook | this.state |
| Lifecycle Methods | useEffect hook | componentDidMount, etc. |
| Recommended? | Yes | No (legacy) |
Conclusion
- Use functional components for better performance and readability.
- Functional components support React Hooks (
useState,useEffect, etc.). - Class components are considered outdated and should be avoided unless maintaining legacy code.