Why it is Recommended to use Functional Components over Class Components ? - GeeksforGeeks (2024)

Last Updated : 17 Dec, 2023

Summarize

Comments

Improve

In this article, we will learn about the use of the functional component over the class component. In React JS, there are two main types of components:

  • Functional Components
  • Class Components.

Functional Components are JavaScript functions that take in props as an argument and return a React element to be rendered. They are simpler and less verbose than class components and can be easier to reason about and test. They are also generally faster to render.

Class Components, on the other hand, are JavaScript classes that extend React.Component class. They have more features and capabilities than functional components, such as state and lifecycle methods. They are also useful for more complex components, such as ones that need to manage an internal state or handle user events.

Reasons to use Functional Component over Class Components

There are a few reasons why it’s recommended to use functional components over class components in React:

  • Simplicity: Functional components are simpler and easier to understand than class components. They don’t have the added complexity of lifecycle methods, state, and this binding.
  • Performance: Functional components are more performant than class components. They don’t have the added overhead of creating a new instance for each render and also functional components can use the React Hooks which makes it more performant.
  • Easier to test: Functional components are easier to test than class components. Because they are just plain JavaScript functions, they can be tested with standard JavaScript testing tools like Jest.
  • Easier to reuse: Functional components are easier to reuse than class components. Because they are just plain JavaScript functions, they can be easily reused across different parts of your application.
  • Easier to reason about Functional components are easier to reason about than class components. Because they are just plain JavaScript functions, their behavior is more predictable and easier to understand.
  • Hooks: Functional components can use the React hooks, which allows you to use state and other React features in functional components, while class components can’t. Refer to this GFG Article to have better a understanding of Hooks – Link.

Steps to Create the React Application And Installing Module:

Step 1: To create a react app, install react modules by using npx command.

npx create-react-app project name

Step 2: After creating your react project, move into the folder to perform different operations by using the below command.

cd project name

Project Structure:

Why it is Recommended to use Functional Components over Class Components ? - GeeksforGeeks (1)

Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

Example 1: React functional components are defined using ES6 arrow functions or function declarations. The code used below is in the FunctionalComponent.js file that will be present in the Component folder. Here’s an example of a basic functional component in React:

Javascript

import './App.css';

import FunctionalComponent from

'./Component/FunctionalComponent';

function App() {

return (

<div className="App">

<FunctionalComponent name="GFG" />

</div>

);

}

export default App;

Javascript

import React from 'react'

const FunctionalComponent = (props) => {

return (

<div>

<h1>

This is an example of

Functional Component.

</h1>

<p>

name passed from App Component to

Functional Component using props

</p>

<h2>{props.name}</h2>

</div>

)

}

export default FunctionalComponent;

Step: Open the terminal and type the following command to host the project on the local server.

npm start

Output:

Why it is Recommended to use Functional Components over Class Components ? - GeeksforGeeks (2)

Both the functional declaration and arrow function code will have the same output

Steps to convert any Class Component to a Functional Component:

  • Import all the necessary libraries.
  • Replace the class declaration with the function declaration.
  • We simply don’t use this in the functional component, hence remove this from the code. for eg (Replace this.props with simple props)
  • You have to pass all the props as we do with a normal function.
  • Replace this.state with useState() hook,
  • Replace all the lifecycle methods like ComponentDidMount() with useEffect() hook.
  • At the end remove the render() method and return the component’s JSX directly from the function.

Example 2: Below is the code for the App.js file which will remain the same for both class and functional components.

Javascript

// Below is the code for App.js file and

// it will remain same for both class

// component and functional component.

import './App.css';

import MyComponent from './Component/MyComponent';

function App() {

return (

<div className="App">

<MyComponent name="GFG-Counter" />

</div>

);

}

export default App;

Javascript

// Class component

import React, { Component } from 'react';

class MyComponent extends Component {

constructor(props) {

super(props);

this.state = {

count: 0,

};

}

componentDidMount() {

console.log('Component mounted');

}

handleClick = () => {

this.setState({ count: this.state.count + 1 });

};

render() {

return (

<div>

<h1>{this.props.name}</h1>

<p>Count: {this.state.count}</p>

<button onClick={this.handleClick}>

Click me

</button>

</div>

);

}

}

export default MyComponent;

Step: Open the terminal and type the following command to host the project on the local server.

npm start

Output:

Why it is Recommended to use Functional Components over Class Components ? - GeeksforGeeks (3)

Output



A

aftab_a

Why it is Recommended to use Functional Components over Class Components ? - GeeksforGeeks (4)

Improve

Next Article

When to use a Class Component over a Function Component in ReactJS ?

Please Login to comment...

Why it is Recommended to use Functional Components over Class Components ? - GeeksforGeeks (2024)
Top Articles
What Is A Bond ETF And Is It A Good Investment? | Bankrate
commercial property coverage forms (CP)
Whas Golf Card
Where are the Best Boxing Gyms in the UK? - JD Sports
Warren Ohio Craigslist
Amc Near My Location
Mountain Dew Bennington Pontoon
Cad Calls Meriden Ct
Obituary (Binghamton Press & Sun-Bulletin): Tully Area Historical Society
Displays settings on Mac
Waive Upgrade Fee
Texas (TX) Powerball - Winning Numbers & Results
Craigslist/Phx
World Cup Soccer Wiki
Used Wood Cook Stoves For Sale Craigslist
Jasmine Put A Ring On It Age
Seafood Bucket Cajun Style Seafood Restaurant in South Salt Lake - Restaurant menu and reviews
Blue Beetle Showtimes Near Regal Swamp Fox
5808 W 110Th St Overland Park Ks 66211 Directions
Busted Newspaper S Randolph County Dirt The Press As Pawns
Void Touched Curio
Overton Funeral Home Waterloo Iowa
Baywatch 2017 123Movies
Costco Gas Foster City
Craigslist Free Stuff Santa Cruz
The Exorcist: Believer (2023) Showtimes
H12 Weidian
My Homework Lesson 11 Volume Of Composite Figures Answer Key
Satisfactory: How to Make Efficient Factories (Tips, Tricks, & Strategies)
Persona 5 Royal Fusion Calculator (Fusion list with guide)
Phoebus uses last-second touchdown to stun Salem for Class 4 football title
Minnick Funeral Home West Point Nebraska
Play It Again Sports Norman Photos
48 Oz Equals How Many Quarts
Klsports Complex Belmont Photos
55Th And Kedzie Elite Staffing
Babydepot Registry
Sf Bay Area Craigslist Com
What Happened To Father Anthony Mary Ewtn
Minecraft Jar Google Drive
Upstate Ny Craigslist Pets
Agematch Com Member Login
Empires And Puzzles Dark Chest
Daly City Building Division
Oppenheimer Showtimes Near B&B Theatres Liberty Cinema 12
[Teen Titans] Starfire In Heat - Chapter 1 - Umbrelloid - Teen Titans
Walmart Careers Stocker
Tyco Forums
Access to Delta Websites for Retirees
Tommy Gold Lpsg
Noelleleyva Leaks
Latest Posts
Article information

Author: Mrs. Angelic Larkin

Last Updated:

Views: 6511

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Mrs. Angelic Larkin

Birthday: 1992-06-28

Address: Apt. 413 8275 Mueller Overpass, South Magnolia, IA 99527-6023

Phone: +6824704719725

Job: District Real-Estate Facilitator

Hobby: Letterboxing, Vacation, Poi, Homebrewing, Mountain biking, Slacklining, Cabaret

Introduction: My name is Mrs. Angelic Larkin, I am a cute, charming, funny, determined, inexpensive, joyous, cheerful person who loves writing and wants to share my knowledge and understanding with you.