How to Create Components in React (Class and Function)
In React, components are the building blocks of the UI. You can create them in two primary ways: using Class Components or Function Components. Let’s explore both with examples.
1. Creating Function Components (Modern and Recommended)
Function components are simpler and are the most common way to build components in modern React (especially with the introduction of Hooks).
Syntax:
import React from 'react'; function Greeting() { return ( <h1>Hello, welcome to my blog!</h1> ); } export default Greeting;
Or using an Arrow Function:
import React from 'react'; const Greeting = () => { return ( <h1>Hello, welcome to my blog!</h1> ); } export default Greeting;
Key Points:
- Simpler and shorter than class components.
- You can use Hooks (like
useState
,useEffect
) inside function components to add features like state and lifecycle methods.
2. Creating Class Components (Older Method)
Before Hooks, class components were the standard way to manage complex behavior like state and lifecycle methods.
Syntax:
import React, { Component } from 'react'; class Greeting extends Component { render() { return ( <h1>Hello, welcome to my blog!</h1> ); } } export default Greeting;
Key Points:
- Must extend
React.Component
. - Requires a
render()
method that returns the JSX. - Used for components that needed state or lifecycle methods (before Hooks were introduced).
Quick Comparison:
Feature | Function Component | Class Component |
---|---|---|
Syntax | Simple and concise | Verbose |
State Management | Using Hooks | Using this.state |
Lifecycle Methods | Using Hooks | Using lifecycle methods like componentDidMount |
Recommended for new apps | ✅ Yes | ❌ No (only if needed for legacy code) |
✅ Tip: Always prefer function components unless you're maintaining an old codebase. They are lighter, easier to read, and fully capable thanks to Hooks.