Functional vs. Class Components

Discover the "why" behind modern React. Master the two component paradigms, understand Hooks, and learn why the future is functional.

Lesson ProgressStep 1 of 9
class Welcome...
this.state = { count: 0 }
function Welcome...
const [count, setCount] = ...
setCount(count + 1)
useEffect(...)
🏆
0 EXP

Welcome! Let's explore the two ways to build components in React: Class and Functional.

// React Component Evolution

What is a React Component?

Think of components as the fundamental building blocks of a React application, just like Lego bricks. Each component is a self-contained, reusable piece of code that controls a part of the UI (User Interface).

A component can be as small as a button or as large as an entire page. They accept inputs called `props` (short for properties) and return React elements that describe what should appear on the screen. There are two main types: Class and Functional.

System Check

What is the primary role of a React component?

Advanced Holo-Simulations

0 EXP

Log in to unlock these advanced training modules and test your skills.


Achievements

🏆
Syntax Master

Distinguish the core syntax of Class and Functional components.

🏗️
State Whiz

Correctly identify state management in both component types.

✍️
Refactor Expert

Successfully refactor a class component to a functional one.

Mission: Refactor a Class Component

Convert this Class Component into a Functional Component using the `useState` and `useEffect` Hooks. Our AI assistant will provide real-time feedback.

A.D.A. Feedback:

> System integrity looks stable. Code is valid.

Challenge: Sort the Concepts

Drag the concepts from the bank into their correct category.

Concept Bank

render()
useState()
this.state
useEffect()
constructor()
No 'this' keyword

Class Components

Functional Components

Challenge: Complete the Hook

Fill in the missing parts of the `useState` Hook declaration.

const [, ] = (0);

Consult A.D.A.

Community Holo-Net

Peer Project Review

Submit your "Refactor a Class" project for feedback from other Net-Runners.

The Complete Guide: Functional vs. Class Components in React

When you begin your journey with React, you'll immediately encounter two ways to create components: **Functional Components** and **Class Components**. While both can achieve the same results, the React ecosystem has undergone a significant paradigm shift. Understanding the "why" behind this shift is crucial to becoming a proficient React developer.

Historically, Class Components were the only way to manage state and access lifecycle methods. Functional components were just "dumb" presentational components. This all changed in 2018 with the introduction of **Hooks**, which allowed functional components to do everything classes could, and more, but with a simpler and more powerful API.

1. Syntax: Verbose vs. Concise

The most obvious difference is the syntax. Class components are ES6 classes, requiring more boilerplate, while functional components are plain JavaScript functions.

❌ Class Component

import React, { Component } from 'react';

class Welcome extends Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Requires `extends Component`, `this.props`, and a `render()` method.

✔️ Functional Component

import React from 'react';

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

A simple function that receives `props` as an argument.

2. State Management: `this.setState` vs. `useState`

This is the most significant functional difference. Class state is a single, monolithic object. Functional state is managed with the `useState` Hook, which lets you create multiple, independent state variables.

  • Class State: Initialized in the `constructor`. Updated with `this.setState()`. When you call `this.setState()`, React **merges** your update with the existing state object.
  • Functional State (`useState`): Returns a pair: the current value and a function to update it. The update function **replaces** the old value. You must manage objects manually if that's what you store.
// CLASS
constructor(props) {
  super(props);
  this.state = { count: 0, name: 'User' };
}
//...
this.setState({ count: 1 }); // Merges state: { count: 1, name: 'User' }

// FUNCTIONAL
const [count, setCount] = useState(0);
const [name, setName] = useState('User');
//...
setCount(1); // Replaces state. State is managed separately.

3. Lifecycle Methods vs. The `useEffect` Hook

Classes have a complex set of lifecycle methods to run code at different times (`componentDidMount`, `componentDidUpdate`, `componentWillUnmount`). Functional components unify all of these into a single API: the `useEffect` Hook.

Mapping Lifecycle to `useEffect`:

  • `componentDidMount` (Run on mount):
    useEffect(() => {...}, []); (Empty dependency array)
  • `componentDidUpdate` (Run on prop/state change):
    useEffect(() => {...}, [prop, state]); (Dependency array)
  • `componentWillUnmount` (Run on unmount):
    useEffect(() => { return () => {...cleanup...} }, []); (Return a cleanup function)

`useEffect` is more powerful because it groups logic by **concern** (e.g., all data-fetching logic in one `useEffect`) rather than by **lifecycle method** (splitting data-fetching logic between `componentDidMount` and `componentDidUpdate`).

4. The `this` Keyword: The Elephant in the Room

In class components, you must constantly manage the `this` keyword. JavaScript's `this` is dynamic, so event handlers in classes (like `onClick={this.handleClick}`) will lose their context unless you explicitly `.bind(this)` in the constructor or use arrow functions. This is a common source of bugs.

**Functional components have no `this` keyword.** You just define functions and variables in the component's scope. This closure-based approach is far more intuitive and less error-prone.

5. Code Reusability: HOCs vs. Custom Hooks

This is the knockout blow. In the past, to share stateful logic between class components, you had to use complex patterns like Higher-Order Components (HOCs) or Render Props. These patterns led to "wrapper hell" and made code hard to follow.

Functional components introduced **Custom Hooks**. A custom hook is just a JavaScript function whose name starts with "use" that can call other Hooks. It's a simple, elegant way to extract and reuse stateful logic without adding extra components to the tree.

// CUSTOM HOOK
function useDocumentTitle(title) {
  useEffect(() => {
    document.title = title;
  }, [title]);
}

//... In your component
useDocumentTitle('My Page Title'); // Simple, reusable, and clean.
Key Takeaway: Always use **Functional Components with Hooks** for any new React code. They are more concise, easier to read, and offer a superior way to manage state, side effects, and reusable logic (Custom Hooks). You only need to learn Class Components to maintain older codebases.

React Components Glossary

Component
A reusable, self-contained piece of UI (e.g., a button, a form, a page). In React, components are the fundamental building blocks.
Props (Properties)
A read-only object of data passed from a parent component to a child component. It's how components communicate.
State
Data that is managed *inside* a component and can change over time. A change in state causes the component to re-render.
Class Component
The "older" way. An ES6 class that extends `React.Component`. It uses a `render()` method, `this.state` for state, and lifecycle methods (e.g., `componentDidMount`).
Functional Component
The "modern" way. A standard JavaScript function that accepts `props` and returns JSX. With Hooks, it can manage state and side effects.
Hooks
Special functions (e.g., `useState`, `useEffect`) that let you "hook into" React features (like state and lifecycle) from within functional components.
`useState`
A Hook that adds state to a functional component. It returns an array with the current state value and a function to update it.
`useEffect`
A Hook that lets you perform "side effects" (e.g., data fetching, DOM manipulation, subscriptions) in functional components. It replaces `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount`.
Dependency Array
The second argument to `useEffect`. It's an array of values that the effect "depends on." The effect will only re-run if one of these values changes. An empty array `[]` means the effect runs only once on mount.
`this` (in React Classes)
A keyword in class components that refers to the component instance. It is used to access `this.props`, `this.state`, and `this.setState`. Its context can be lost in event handlers, requiring `.bind()` or arrow functions.
Custom Hook
A reusable JavaScript function (name starting with "use") that encapsulates stateful logic by calling other Hooks. This is the modern React pattern for sharing logic, replacing HOCs and Render Props.
Higher-Order Component (HOC)
An advanced legacy pattern. A function that takes a component and returns a new component, usually injecting extra props or logic.

About the Author

Author's Avatar

TodoTutorial Team

Passionate developers and educators making programming accessible to everyone.

This article was written and reviewed by our team of senior React developers, who have extensive experience building large-scale applications and teaching modern React practices.

Verification and Updates

Last reviewed: October 2025.

We strive to keep our content accurate and up-to-date. This tutorial is based on the latest React documentation (React 18+) and is periodically reviewed to reflect industry best practices.

External Resources

Found an error or have a suggestion? Contact us!