Saturday, November 16, 2024
Google search engine
HomeLanguagesWhy it is Recommended to use Functional Components over Class Components ?

Why it is Recommended to use Functional Components over Class Components ?

In React.js, there are two main types of components: 

  • functional components and 
  • class components.

Functional components are basically 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.

In general, functional components are recommended over class components unless you specifically need the additional features provided by class components. With the introduction of hooks in React 16.8, functional components can now also handle state and lifecycle methods, making them even more powerful and versatile. I have mentioned below some more reasons to consider Functional Components over Class components. 

Reasons: 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.

Creating React Project:

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

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

npm start

Project Structure:

React Project File Structure

 Example 1: Create a new Folder called Component to store component files and then Change the current App.js file content to

Javascript




import './App.css';
import FunctionalComponent from 
    './Component/FunctionalComponent';
  
function App() {
    return (
        <div className="App">
            <FunctionalComponent name="GFG" />
        </div>
    );
}
  
export default App;


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:

Here’s the same component using an ES6 arrow function:

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;


Both the above code will have the same output :

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;


  • Code in Class Component  

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;


  • After applying the above-mentioned rules to the class component code. Add the below code to the Component/MyComponent.js

Javascript




// Functional component
import React, { useState, useEffect } from 'react';
  
function MyComponent(props) {
    const [count, setCount] = useState(0);
  
    useEffect(() => {
        console.log('Component mounted');
    }, []);
  
    const handleClick = () => {
        setCount(count + 1);
    };
  
    return (
        <div>
            <h1>{props.name}</h1>
            <p>Count: {count}</p>
            <button onClick={handleClick}>Click me</button>
        </div>
    );
}
  
export default MyComponent;


output for the above code and it will remain the same for both functional and class component

This is just a basic example, and depending on the complexity of the original class component, there may be additional changes needed when converting to a functional component.

Note: It’s important to note that class components are still a valid option in React and can be used in specific cases where it’s necessary to use lifecycle methods or local states. However, in most cases, it’s recommended to use functional components with Hooks instead. 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments