Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Why it is Recommended to use Functional Components over Class Components ?
Next article icon

Migrating from Class Components to Functional Components in React

Last Updated : 15 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 help of functional components, it has become easier to manage the state and lifecycle of a component. We don't need to define any class. Directly declare the components and use them wherever required. The code is quite simple, easy to understand, reusable, and manageable.

Table of Content

  • The State Management in React using class and functional component
  • The Lifecycle in React using class and functional component
  • Conclusion

The State Management in React using class and functional component

Class Component state: setState:

To add a state to a class component using the setState, initialize the state in the constructor and declare the methods with the class itself. To set the state we need to create an additional function defining the update that is to be done in the state.

Example: Below is an example of class component state.

JavaScript
import React from 'react';  class Gfgarticle extends React.Component {     constructor(props) {         super(props);         this.state = {             count: 0         };         this.increment = this.increment.bind(this);     }      increment() {         this.setState({ count: this.state.count + 1 });     }     render() {         return (             <div>                 <h1>Counter Program</h1>                 <p>You clicked {this.state.count} times</p>                 <button onClick={this.increment}>Increment</button>             </div>         );     } }  export default Gfgarticle; 

Functional component state: useState

While using the useState as a Functional Component, initialize the state with some initial value and declare the function which whenever called helps to make updating the state.

Example: Below is an example of functional component state.

JavaScript
import React, { useState } from "react";  function Gfgarticle() {     // Here is a react Hook      const [count, setCount] = useState(0);      return (         <div>             <h1>COUNTER PROGRAM</h1>             <p>You clicked {count} times</p>             <button onClick={() => setCount(count + 1)}>                 Increment             </button>         </div>     ) } export default Gfgarticle; 

Now let's have a check on the lifecycle in react using both the class and functional component

The Lifecycle in React using class and functional component

Class Component LifeCycle

The Lifecycle of a class component required declaration of several sets of methods which includes componentDidMount, componentDidUpdate, componentWillUnmount, etc.

Example: Below is an example of class component lifecycle.

JavaScript
import React from 'react';  class Gfgarticle extends React.Component {     constructor(props) {         super(props);         this.state = {             count: 0         };         this.increment = this.increment.bind(this);     }     static getDerivedStateFromProps(props, state) {         console.log('getDerivedStateFromProps called', props, state);         return null;     }      componentDidMount() {         console.log('componentDidMount called');     }      shouldComponentUpdate(nextProps, nextState) {         console.log('shouldComponentUpdate called',                       nextProps, nextState);         return true;     }      getSnapshotBeforeUpdate(prevProps, prevState) {         console.log('getSnapshotBeforeUpdate called',                      prevProps, prevState);         return null;     }      componentDidUpdate(prevProps, prevState, snapshot) {         console.log('componentDidUpdate called',                       prevProps, prevState, snapshot);     }      componentWillUnmount() {         console.log('componentWillUnmount called');     }      handleClick = () => {         this.setState(prevState => ({             count: prevState.count + 1         }));     };     increment() {         this.setState({ count: this.state.count + 1 });     }     render() {         return (             <div>                 <h1>Counter Program</h1>                 <p>You clicked {this.state.count} times</p>                 <button onClick={this.handleClick}>Increment</button>             </div>         );     } }  export default Gfgarticle; 

You can observe the lifecycle method calls in the console as you interact with the component, helping you understand the sequence of events during the component's lifecycle.

Here is the result of the above code

Screenshot-2024-03-09-032039

Functional Component LifeCycle

In the functional component, we simply use the useEffect hook to keep a track of the side effects and perform the cleanup tasks.

The same above lifecycle event using functional component is given as below:

JavaScript
import React, { useState, useEffect } from "react";  function Gfgarticle() {     // Here is a react Hook      const [count, setCount] = useState(0);     useEffect(() => {         console.log('Component mounted');         return () => {             console.log('Component will unmount');         };     }, []);      useEffect(() => {         console.log('Count updated:', count);     }, [count]);      const handleClick = () => {         setCount(prevCount => prevCount + 1);     };     return (         <div>             <p>You clicked {count} times</p>             <button onClick={handleClick}>                 Increment             </button>         </div>     ) } export default Gfgarticle; 

The life cycle using the functional component can easily be seen in the console.

Here is the result of the above code

Screenshot-2024-03-09-032719

Conclusion:

In conclusion, while class components have been a cornerstone of React development for many years, they come with certain drawbacks, including complexity, limited reusability, and potential performance overhead. With the introduction of hooks in React, functional components have become the preferred way to define components, offering a simpler, more declarative, and more efficient approach to building React applications.


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

Y

yogita14cdy
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Hooks

Similar Reads

  • 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
    2 min read
  • How to Call Parent Components's Function from Child Component in React ?
    In React, it is very important to manage communication between components for building flexible and maintainable applications. Sometime, you need to trigger a function defined in a parent component from a child component. In this article, we'll see how to achieve this in React by passing down functi
    3 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
    4 min read
  • When to use a Class Component over a Function Component in ReactJS?
    ReactJS provides two main ways to create components: Class Components and Function Components. With the introduction of React Hooks in version 16.8, Function Components became more powerful and are now commonly preferred. However, there are still scenarios where Class Components might be a better ch
    3 min read
  • How to create a Functional Component 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 b
    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 b
    2 min read
  • How does a pure component differ from a functional component?
    React provides two main types of components: pure components and functional components. Understanding the differences between these two types is important for effective React development. In this article, we will learn about pure components and functional components, along with discussing the signif
    4 min read
  • Differences Between Functional Components and Class Components
    In React, components are the building blocks of the user interface, and you can define them in two ways: Functional Components and Class Components. Both are used to build UI elements, but they differ in syntax, but they differ in syntax, state management, lifecycle methods, and other features. With
    4 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
    3 min read
  • React JS Component Composition and Nested Components
    React JS Component Composition allows you to build complex UIs by combining smaller, reusable components. Nested Components refer to components that are used within other components, enabling a modular and structured approach to building React applications. Table of Content Component CompositionNest
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences