React Components: Function-Based vs Class-Based

React Components: Function-Based vs Class-Based

Comparing the two approaches with examples

Choosing function based components or class based components is a common question a lot of us face when starting your React journey. In this blog, we will talk about both of these approaches and guide you along with examples.

Function-Based Components

In programming, we make functions to reuse the code and make it more readable. A function is just a block of code given some label, and we can execute that block of code by using that label i.e function name.

Our web applications are simply made of HTML, CSS and JavaScript. And in React we simply breakdown our apps into smaller parts called components. So, components are merely the HTML, CSS, JS chunks.

Example:

import React from 'react';

const FunctionComponent = () => {
  return <p>Hello, Function Component!</p>;
};

Click here to run code

Features:

  1. Simplicity: Functions are concise, making the code easy to read and maintain.

  2. Nothis Keyword: Eliminates confusion around the this keyword, simplifying the component structure.

Class-Based Components

Class-based components have been a traditional way of defining React components, incorporating the concepts of ES6 classes.

Example:

import React, { Component } from 'react';

class ClassComponent extends Component {
  render() {
    return <p>Hello, Class Component!</p>;
  }
}

Click here to run code

Features:

  1. Lifecycle Methods: Enables the use of lifecycle methods like componentDidMount, componentDidUpdate, etc.

  2. State Management: Supports local state management using this.state and this.setState().

When to Use Function-Based Components?

  1. Functional Paradigm: When adhering to a functional programming paradigm or following a more functional approach.

  2. Simplicity: For simpler components without the need for state or lifecycle methods.

  3. Hooks: When utilizing React Hooks for state and side effects.

Example: Function-Based Component with Hooks

import React, { useState, useEffect } from 'react';

const FunctionWithHooks = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

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

Click here to run code

When to Use Class-Based Components?

  1. Legacy Codebases: When working with older codebases that extensively use class components.

  2. Lifecycle Methods: For components requiring lifecycle methods for tasks like data fetching or DOM manipulation.

  3. Local State: When managing local state using this.state is necessary.

Example: Class-Based Component with State

import React, { Component } from 'react';

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

  componentDidMount() {
    document.title = `Count: ${this.state.count}`;
  }

  componentDidUpdate() {
    document.title = `Count: ${this.state.count}`;
  }

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

Click here to run code

Conclusion

  • Function-based components and class-based components are both essential to React development, providing different approaches for doing the same thing.

  • The introduction of hooks has allowed function components to handle state and side effects, blurring the distinction between the two techniques.

  • So, you will find old code written using class based syntax and new with function based syntax.

  • You should understand the differences between each so that you can work on projects or third party packages that use either or both of the two approaches.

    Thanks for Reading!