*
Previous React-QA-10 Manage state with Redux or NgRx Next

Functional vs Class Components in React

⚛️ Functional vs Class Components in React

🔍 What Are React Components?

React components are reusable building blocks of a user interface. They can be defined in two main ways: Functional Components and Class Components.

🧠 Functional Components

  • Defined using JavaScript functions or arrow functions
  • Stateless by default, but can use Hooks like useState and useEffect
  • Simpler syntax and easier to test
  • Preferred in modern React development

Example

import React, { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Add</button>
    </div>
  );
}
  

🏛️ Class Components

  • Defined using ES6 classes that extend React.Component
  • Can manage state using this.state
  • Use lifecycle methods like componentDidMount, componentDidUpdate
  • More verbose and complex than functional components

Example

import React, { Component } from "react";

class Counter extends Component {
  constructor() {
    super();
    this.state = { count: 0 };
  }

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

  render() {
    return (
      <div>
        <h2>Count: {this.state.count}</h2>
        <button onClick={this.increase}>Add</button>
      </div>
    );
  }
}
  

⚔️ Key Differences

Feature Functional Component Class Component
Syntax Function or arrow function ES6 class
State Management Hooks (e.g., useState) this.state
Lifecycle Hooks (e.g., useEffect) Lifecycle methods
Code Complexity Simpler More verbose
Performance Generally better Can be heavier
Modern Usage Preferred Legacy support

✅ Summary

Functional components are now the standard in React thanks to Hooks, offering cleaner syntax and better performance. Class components are still supported but are less commonly used in new projects.

Back to Index
Previous React-QA-10 Manage state with Redux or NgRx Next
*
*