Tool for HR, Hiring Managers, and the Leadership Team

Difference between functional and class components?

In React, components can be created in two ways:

  1. Functional Components

  2. Class Components

Today, functional components are the recommended approach because of Hooks.

1. Functional Components

A functional component is simply a JavaScript function that returns JSX.

function Welcome() {
  return <h1>Hello World</h1>;
}

Or using arrow function:

const Welcome = () => {
  return <h1>Hello World</h1>;
};

Features

  • Simpler and cleaner syntax

  • Easier to read and test

  • Uses Hooks (useState, useEffect, etc.)

  • Better performance optimization in modern React

  • Preferred in modern React applications

State in Functional Components

Earlier, functional components were stateless.

Now Hooks allow state handling:

import React, { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
      {count}
    </button>
  );
}

2. Class Components

Class components are ES6 classes that extend React.Component.

import React, { Component } from "react";

class Welcome extends Component {
  render() {
    return <h1>Hello World</h1>;
  }
}

Features

  • Uses lifecycle methods

  • Has this keyword

  • More boilerplate code

  • Used heavily before Hooks were introduced

State in Class Components

class Counter extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      count: 0
    };
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <button onClick={this.increment}>
        {this.state.count}
      </button>
    );
  }
}

Key Differences

Feature Functional Component Class Component
Syntax Simple function ES6 class
State Management Hooks (useState) this.state
Lifecycle Handling Hooks (useEffect) Lifecycle methods
this keyword Not used Used
Boilerplate Less More
Readability Easier More complex
Performance Generally better in modern React Slightly heavier
Current Recommendation Preferred Mostly legacy

Lifecycle Difference

Class Component Lifecycle

componentDidMount()
componentDidUpdate()
componentWillUnmount()

Functional Component Equivalent

Using useEffect:

useEffect(() => {
  // componentDidMount logic

  return () => {
    // componentWillUnmount logic
  };
}, []);

Interview-Friendly Answer

Functional components are JavaScript functions that return JSX and use Hooks for state and lifecycle management.
Class components are ES6 classes that extend React.Component and use lifecycle methods and this.state.
Modern React prefers functional components because they are simpler, cleaner, and easier to maintain.