How do you create components in React
React components can be created in two main ways:
Function Components (Modern, with Hooks)
Class Components (Legacy, but still used in older codebases)
1. Function Components (Recommended)
Simple, reusable, and leverage React Hooks for state and lifecycle features.
Basic Syntax
function Greeting(props) { return <h1>Hello, {props.name}!</h1>; }
Usage:
<Greeting name="Alice" /> // Renders: <h1>Hello, Alice!</h1>
With State (Using useState
Hook)
import { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); // State initialization return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
Arrow Function (Preferred in Modern React)
const Greeting = ({ name }) => { return <h1>Hello, {name}!</h1>; };
2. Class Components (Legacy)
Used in older React codebases (pre-Hooks).
Basic Syntax
import React from 'react'; class Greeting extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } }
Usage:
<Greeting name="Bob" /> // Renders: <h1>Hello, Bob!</h1>
With State (this.state
& this.setState
)
class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; // Initialize state } render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Increment </button> </div> ); } }
Key Differences
Feature | Function Component | Class Component |
---|---|---|
Syntax | Simpler, uses functions. | Uses class and extends React.Component . |
State | Uses useState Hook. | Uses this.state and this.setState . |
Lifecycle | Uses useEffect Hook. | Uses methods like componentDidMount() . |
Performance | Slightly faster (no this binding). | Slightly slower due to class overhead. |
Modern Usage | ✅ Preferred in new projects. | ⚠️ Legacy (but still supported). |
Best Practices
Use Function Components for new projects (with Hooks).
Keep Components Small (Single Responsibility Principle).
Name Components in PascalCase (e.g.,
UserProfile
, notuserProfile
).Use Arrow Functions for concise syntax.
Type Safety (Optional): Use TypeScript or PropTypes for props validation.
Example: A Reusable Button
Component
import { useState } from 'react'; const Button = ({ label, onClick }) => { return ( <button onClick={onClick} style={{ padding: '10px 20px', backgroundColor: 'blue', color: 'white' }} > {label} </button> ); }; // Usage: <Button label="Click Me" onClick={() => alert('Clicked!')} />
Summary
Function Components = Modern, simpler, Hooks-based.
Class Components = Legacy, state via
this.setState
.React Hooks (
useState
,useEffect
) make functions as powerful as classes.