React: Functional vs Class-Based Components

Naveen Kumar SNaveen Kumar S
2 min read

What Are React Components?

In React, components are building blocks of your UI. They’re like reusable chunks of code that return JSX (HTML-like syntax).

There are two types:

  • Class Components

  • Functional Components

Class Components:

Class components were the standard way of writing components before React 16.8. Here’s how they look:

import React, { Component } from "react";

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

Key Features of Class Components:

  • Requires class keyword and extends React.Component

  • Uses render() method

  • Accesses props with this.props

  • Uses lifecycle methods like componentDidMount, componentDidUpdate, componentWillUnmount

Functional Components:

Functional components are simply JavaScript functions that return JSX. Here’s how they look:

function Welcome(props) {
  return <h1>Hello, {props.name}!</h1>;
}
  • Simpler syntax – just a function!

  • With React Hooks (added in React 16.8), they can manage state and lifecycle.

  • Encourages cleaner, more readable code.

Class vs Functional – A Quick Comparison:

FeatureClass ComponentFunctional Component
SyntaxES6 ClassJavaScript Function
State Managementthis.state, this.setState()useState() Hook
Lifecycle MethodscomponentDidMount()useEffect() Hook
Code SimplicityMore boilerplateLess code, more readable

Class Component with State:

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

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

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

Functional Component with State:

import React, { useState } from "react";

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Conclusion:

Functional and Class Components both serve the same purpose: building UI in React. The difference lies in syntax and how they handle aspects such as state and lifecycle.

With Hooks, functional components now possess superpowers that previously only existed in classes. So, unless there's a specific need, go functional!

0
Subscribe to my newsletter

Read articles from Naveen Kumar S directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Naveen Kumar S
Naveen Kumar S

Naveen Kumar is a Computer Science student at Garden City University, passionate about frontend development and modern web technologies. I specialize in creating responsive web applications using React.js and Tailwind CSS, with a focus on UI/UX design, smooth animations, and performance optimization.