Both Functional Components and Class Components are essential in React for building reusable UI elements, but they are structured differently and have unique characteristics. Functional Components are simpler and more concise, especially with the introduction of React Hooks, which allow them to manage state and side effects. On the other hand, Class Components are more traditional, relying on lifecycle methods and the ‘this’ keyword for handling state and events.
Functional Components vs Class Components
Here is a detailed comparison of Functional Components and Class Components based on various features
Feature | Functional Components | Class Components |
---|---|---|
State Management | Can use Hooks (e.g., useState, useReducer) for state management | Uses this.state and this.setState() for state management |
Lifecycle Methods | Uses useEffect Hook for lifecycle methods (e.g., componentDidMount, componentWillUnmount) | Uses built-in lifecycle methods (e.g., componentDidMount, componentDidUpdate, componentWillUnmount) |
Rendering | Returns JSX directly inside the function | Uses a render() method to return JSX |
Performance | Faster and more lightweight due to simpler structure | Slightly heavier due to the overhead of class instances |
Hooks | Can use React hooks (useState, useEffect, etc.) | Cannot use hooks; relies on lifecycle methods and state |
This Keyword | Does not use this keyword | Uses this to access props and state |
Code Complexity | Less boilerplate code, easier to write and understand | More boilerplate code, especially for state and methods |
Use in Modern React | Preferred for new development, especially with hooks | Used in legacy codebases or when hooks are not supported |
Event Handling | Simple and direct event handling | Requires method binding for event handling |
Functional Components
A functional component is a simpler way to define components in React using JavaScript functions. Unlike class components, functional components do not require a constructor or lifecycle methods. They are typically used for components that are presentational and do not manage complex state or lifecycle events
Syntax
const Car=()=> {
return <h2>Hi, I am also a Car!</h2>;
}
import React, { useState } from "react";
const FunctionalComponent = () => {
const [count, setCount] = useState(0);
const increase = () => {
setCount(count + 1);
}
return (
<div style={{ margin: '50px' }}>
<h1>Welcome to Techappss </h1>
<h3>Counter App using Functional Component : </h3>
<h2>{count}</h2>
<button onClick={increase}>Add</button>
</div>
)
}
export default FunctionalComponent;

Recent Comments