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.
Example of a Functional Component:
function Greeting() { return <h1>Hello, React!</h1>; } export default Greeting; Why Use Functional Components?
- Simpler and easier to read
- No need for
thiskeyword - Hooks (
useState,useEffect) work only in functional components
2. Class Components (Older Method)
Class components use ES6 classes and render() to return JSX.
Example of a Class Component:
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
-
thiskeyword can be confusing - Cannot use hooks like
useStatedirectly
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). - Class components are outdated and should be avoided unless working with legacy code.
Top comments (0)