Differences between class component and functional component in React js

In React, components are the building blocks of a user interface. There are two main types of components: class components and functional components. The primary difference lies in how they are defined and how the state and lifecycle methods are managed.

React Image

1. Definition syntax:

  • Class Components: Shortcut create - rcc
class MyClassComponent extends React.Component { // ... }
  • Functional Components: Shortcut create - rfc
function MyFunctionalComponent() { // ... } 

 2. State:

  • Class Components:
    • Local states can be set using the this.state and this.setState() methods.
    • Constructors can be used to initialize state and bind methods.
  • Functional Components:
    • Before React 16.8, functional components were stateless, but with the introduction of hooks, functional components can now use state and other features.
    • The useState hook is used to add state to functional components.

3. Lifecycle Methods:
  • Class Component:
    • Have lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.
  • Functional Component:
    • Before React 16.8, functional components did not have lifecycle methods. With Hooks, you can use useEffect to achieve similar functionality.


4. Usage of 'this':

  • Class Component:
    • Need to use this to access props, state, and methods.
  • Functional Component:
    • No this keyword is used. Everything is passed as arguments to the function.


5. Code Conciseness:

  • Class Component:
    • Tend to be more verbose due to the use of class syntax and lifecycle methods.
  • Functional Component:
    • With the introduction of Hooks, functional components are more concise and readable.


6. Performance:

  • Class Component:
    • Generally have a slightly higher performance overhead due to the use of classes and the way they handle updates.
  • Functional Component:
    • With the introduction of Hooks, functional components can achieve similar performance to class components.


7. Hooks:

  • Class Component:
    • Don't use Hooks; instead, they use lifecycle methods for side effects.
  • Functional Component:
    • Use Hooks like useState, useEffect, useContext, etc, for state and side effects.

Functional components with hooks are the recommended way to write components in React, as they offer a more concise and readable syntax, along with the convenience of hooks for handling state and side effects. However, class components are still valid and widely used, especially in projects that have not migrated to functional components with hooks.

Post a Comment

0 Comments