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
How Much Does An RV Cost - Neighbor Blog
Mounting NFS File Systems
Po Box 7250 Sioux Falls Sd
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Avonlea Havanese
Obituary (Binghamton Press & Sun-Bulletin): Tully Area Historical Society
Words From Cactusi
Best Theia Builds (Talent | Skill Order | Pairing + Pets) In Call of Dragons - AllClash
Barstool Sports Gif
Acbl Homeport
Azeroth Pilot Reloaded - Addons - World of Warcraft
Bros Movie Wiki
Springfield Mo Craiglist
Love In The Air Ep 9 Eng Sub Dailymotion
Midlife Crisis F95Zone
Craftology East Peoria Il
Eva Mastromatteo Erie Pa
Mzinchaleft
Palm Coast Permits Online
NHS England » Winter and H2 priorities
Bj Alex Mangabuddy
Unity - Manual: Scene view navigation
Governor Brown Signs Legislation Supporting California Legislative Women's Caucus Priorities
Hampton University Ministers Conference Registration
Jordan Poyer Wiki
How to Make Ghee - How We Flourish
Walmart Pharmacy Near Me Open
Beaufort 72 Hour
Kroger Feed Login
4Oxfun
JVID Rina sauce set1
Marokko houdt honderden mensen tegen die illegaal grens met Spaanse stad Ceuta wilden oversteken
Ou Football Brainiacs
Miles City Montana Craigslist
Angel Haynes Dropbox
Publix Christmas Dinner 2022
Craftsman Yt3000 Oil Capacity
Motor Mounts
Kamzz Llc
4083519708
Second Chance Apartments, 2nd Chance Apartments Locators for Bad Credit
Pain Out Maxx Kratom
6576771660
Here's Everything You Need to Know About Baby Ariel
Lady Nagant Funko Pop
Crigslist Tucson
Devotion Showtimes Near Showplace Icon At Valley Fair
552 Bus Schedule To Atlantic City
Diccionario De Los Sueños Misabueso
Sam's Club Fountain Valley Gas Prices
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.