The Wayback Machine - https://web.archive.org/web/20241117232351/https://www.geeksforgeeks.org/differences-between-functional-components-and-class-components/
Open In App

Differences between Functional Components and Class Components

Last Updated : 02 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn about the differences between functional and class components in React with the help of an example. We will create a counter and implement it using both class and functional components to understand the differences practically.

Functional Components

Functional components are some of the more common components that will come across while working in React. These are simply JavaScript functions. We can create a functional component to React by writing a JavaScript function.

Syntax:

const Car=()=> {
return <h2>Hi, I am also a Car!</h2>;
}

Counter using Functional Components

Example:

Javascript




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 Geeks for Geeks </h1>
            <h3>Counter App using Functional Component : </h3>
            <h2>{count}</h2>
            <button onClick={increase}>Add</button>
        </div>
    )
}
  
export default FunctionalComponent;


Output:

Class Component

This is the bread and butter of most modern web apps built in ReactJS. These components are simple classes (made up of multiple functions that add functionality to the application).

Syntax:

class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}

Counter using Class Components

Example:

Javascript




import React, { Component } from "react";
  
class ClassComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            count: 0
        };
        this.increase = this.increase.bind(this);
    }
  
    increase() {
        this.setState({ count: this.state.count + 1 });
    }
  
    render() {
        return (
            <div style={{ margin: '50px' }}>
                <h1>Welcome to Geeks for Geeks </h1>
                <h3>Counter App using Class Component : </h3>
                <h2> {this.state.count}</h2>
                <button onClick={this.increase}> Add</button>
  
            </div>
        )
    }
}
  
export default ClassComponent;


Output:

 

 

In the above example, for functional components, we use hooks (useState) to manage the state. If you write a function component and realize you need to add some state to it, previously you had to convert it to a class component. Now you can use a Hook inside the existing function component to manage the state and no need to convert it into the Class component. Hooks are a new addition to React 16.8. They let you use state and other React features without writing a class. Instead of Classes, one can use Hooks in the Functional component as this is a much easier way of managing the state. Hooks can only be used in functional components, not in-class components.

Functional Components vs Class Components:

                         Functional Components                                            Class Components                
A functional component is just a plain JavaScript pure function that accepts props as an argument and returns a React element(JSX). A class component requires you to extend from React. Component and create a render function that returns a React element.
There is no render method used in functional components. It must have the render() method returning JSX (which is syntactically similar to HTML)
Functional components run from top to bottom and once the function is returned it can’t be kept alive. The class component is instantiated and different life cycle method is kept alive and is run and invoked depending on the phase of the class component.
Also known as Stateless components as they simply accept data and display them in some form, they are mainly responsible for rendering UI. Also known as Stateful components because they implement logic and state.
React lifecycle methods (for example, componentDidMount) cannot be used in functional components. React lifecycle methods can be used inside class components (for example, componentDidMount).

Hooks can be easily used in functional components to make them Stateful.

Example:

const [name,SetName]= React.useState(' ')

It requires different syntax inside a class component to implement hooks.

Example:

constructor(props) {
   super(props);
   this.state = {name: ' '}
}
Constructors are not used. Constructor is used as it needs to store state. 


Previous Article
Next Article

Similar Reads

Differences between Functional and Non-functional Testing
What is Functional Testing?Functional testing is a type of software testing in which the system is tested against the functional requirements and specifications. Functional testing ensures that the requirements or specifications are properly satisfied by the application. This type of testing is particularly concerned with the result of processing.
2 min read
Why it is Recommended to use Functional Components over Class Components ?
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
4 min read
Migrating from Class Components to Functional Components in React
React version 16.8.0 or higher allows users to write the functional components without the use of class components. Using class components, we need to write the whole class to interact with the state and lifecycle of the component. The code was quite complex and harder to understand which led to lower performance and limited usability. With the hel
4 min read
How to Create Functional Components using Vue Loader ?
Vue.js is a JavaScript framework used in building powerful and beautiful user interfaces. The key feature of Vue.js is its component-based architecture that allows the developers to create reusable and modular components. Functional components, in particular, provide a lightweight and efficient way to build UI elements. In this article, we will lea
3 min read
Why do you need to import React in functional components ?
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. In react, we use JSX, especially in the functional important which is an extension of Javascript it needs the react met
3 min read
How to change states with onClick event in ReactJS using functional components ?
In modern web applications, to change states with onClick event in React JS using functional components is done by Hooks in React as the functional components don't have inbuilt states like class components. With Hooks, state objects are completely independent of each other, so you can have as many state objects as you want. In a single-page applic
2 min read
Advantages of using Functional Components in React
Functional components in React are like a quick and easy way to create pieces of your web app. They're simple, straight to the point, and don't involve a lot of extra code. Think of them as building blocks that help you put together your app without any unnecessary complications. Advantages of using functional components in React:Simplicity: Functi
2 min read
How to create Functional Components in React ?
To create a functional component in React, you define a JavaScript function that returns JSX. These components are stateless and rely on props for data input. Functional components are concise, easy to read, and can utilize React Hooks for managing state and side effects, making them a fundamental building block for React applications. Prerequisite
2 min read
Role of Hooks in Functional Components.
Hooks in React are like new tools that make building components easier. Before, we had to use classes, which were like following strict instructions. But with hooks, we can do the same thing more simply and flexibly directly inside functional components. It's like having a magic connector for building React components, allowing us to manage state,
3 min read
How does React.memo() optimize functional components in React?
React.memo() is a higher-order component provided by React that can help optimize functional components by reducing unnecessary re-renders. Let's explore how it works and how it optimizes functional components: Table of Content Optimizing with React.memo()When to use React.memo() ?Benefits of memoization using React.memo()How to use React.memo() ?C
4 min read
Advantages of using Functional Components with React Hooks
In the past, React mainly used class-based components as its building blocks. However, functional components, which are essentially JavaScript functions that receive props (inputs) and return JSX (rendered content), were limited in their capabilities. With React 16.8 and the introduction of hooks, functional components gained access to features lik
4 min read
Implementing Lazy Loading for Functional Components in React
React is a popular library, maintained by Meta, which is used for building user interfaces and dynamic websites. It offers several techniques to optimize performance and enhance end-user experience. Lazy loading is one such technique that can be used to improve the performance of web applications by deferring the loading of resources until the brow
2 min read
ReactJS Functional Components
Functional Component is one way to create components in a React Application. React.js Functional Components helps to create UI components in a Functional and more concise way. In this article, we will learn about functional components in React, different ways to call the functional component, and also learn how to create the functional components.
6 min read
What are the differences between React.lazy and @loadable/components ?
Before discussing the difference between React.lazy and @loadable/components, let's talk about what are they and why we need them. Both React.lazy and @loadable/components are mainly being used for the process of Code-Splitting. Code-Splitting: Code-Splitting is an optimization technique supported by bundlers like Webpack, Rollup, and Browserify (v
4 min read
Tensorflow.js tf.Functional Class
TensorFlow.js is a JavaScript library for training and deploying machine learning models on web applications and in Node.js. You can develop the machine learning models from scratch using tensorflow.js or can use the APIs provided to train your existing models in the browser or on your Node.js server. Installing TenserFlow.js: There are following t
5 min read
How to convert functional component to class component in ReactJS ?
ReactJS offers two primary ways of creating components: functional components and class components. While functional components are more concise and easier to reason about, there are situations where class components may be necessary with the flexibility to use lifecycle methods and manage the state in a different way. PrerequisitesReact JSReact Fu
2 min read
Difference between Functional Testing and Implementational Testing Approach
Testing simply means an activity that is performed in software engineering to check whether actual result matches expected result or not and to ensure and confirm that there is no defect in software system i.e., Software system is defect-free. There are various types of testing of software that can be performed. Two of them are Functional testing a
2 min read
Difference Between Functional and Logical Programming
Programming paradigm is an approach to solve problems using some programming language or also we can say it is a method to solve a problem using tools and techniques that are available to us following some approach. There are lots of programming languages that are known but all of them need to follow some strategy when they are implemented and this
3 min read
Difference between Functional and Imperative Programming
Functional Programming: Functional Programming, as the name suggests, is a type of programming paradigm that is being created explicitly simply to support a purely functional approach to solving problems. This type of programming is mainly used when solutions are easily expressed in function and have very little physical meaning. It simply helps us
3 min read
Difference Between Unit Tests and Functional Tests
The article focuses on discussing the differences between Unit Testing and Functional Testing. The following topics will be discussed here: What is Unit Testing?What is Functional Testing?Unit Testing vs Functional Testing Let's start discussing each of these topics in detail. What is Unit Testing? Unit Testing includes the testing of each unit or
3 min read
Difference Between Unit, Functional, Acceptance, and Integration Tests
Here, we will discuss the differences between unit testing, functional testing, acceptance testing, and integration testing. Unit Testing It is a testing technique wherein the simple or smallest units of a software program are examined personally for bugs and errors. These smallest units may be examined independently and personally as they do now n
7 min read
Difference between Functional Programming and Object Oriented Programming
What is Functional Programming?In functional programming, we have to build programs using functions. An example of functional programming is Haskell language. What is Object Oriented Programming?Object-oriented programming is built by using classes and objects. In this, we have concepts of encapsulation, inheritance, polymorphism, and Data abstract
3 min read
Difference between Project Management and Functional Management
Within organizational frameworks, there are two different approaches: project management and functional management. The purpose of project management is to deploy temporary teams to accomplish specified targets within predetermined timeframes. Conversely, functional management focusses on long-term objectives and ongoing operations while managing p
4 min read
Differences between Interface and Class in Java
This article highlights the differences between a class and an interface in Java. They seem syntactically similar, both containing methods and variables, but they are different in many aspects. Differences between a Class and an Interface The following table lists all the major differences between an interface and a class in Java language: Class In
4 min read
Differences between ES6 class and ES5 function constructors
In this article, we will discuss the difference between the ES6 class and ES5 function constructors. Both serve the purpose of creating new objects, still, they have some differences between them. ES6 Class constructors: ES6 class constructors work quite the same as class constructors in other object-oriented languages. They are used to create new
2 min read
Functional Programming: Pure and Impure Functions
Functional programming is a programming paradigm that focuses on the use of functions to solve problems. In functional programming, functions are treated as first-class citizens, meaning they can be assigned to variables, passed as arguments, and returned as values. Pure and impure functions are two important concepts in functional programming that
4 min read
Explain the concepts of functional programming in JavaScript
Every program we write follows an approach or style of writing also referred to as a paradigm. Functional programming is a declarative programming paradigm (programming paradigm where we write code in such a way that it describes the result and not the approach). To understand functional programming let's take an example of usual mathematics functi
2 min read
Functional Programming in JavaScript
Functional Programming(FP) is as old as programming but some of us think that it is discovered recently because we found some parts in mathematics but not in the programming world. But nowadays functional programming is in trend. Almost every programming language including Java, Python, JavaScript, etc. is adopting functional programming. It seems
4 min read
Functional programming in JavaScript
Functions are the most important part of functional programming (especially in JavaScript). Functions are the single source that helps developers to perform functional programming. Generally abbreviated as FP which revolves around functions and it is how we use functions that makes our code functional. Without function, there is no FP. So the quest
7 min read
What is a pure functional component in ReactJS ?
What is a JavaScript function? A JavaScript function is a block of code designed to perform a particular task which is executed when it is called. How React functional components are similar to JavaScript functions? Conceptually, components are like JavaScript functions. A functional component is a JavaScript function that returns JSX in React. The
3 min read
three90RightbarBannerImg