DEV Community

Sidra Maqbool
Sidra Maqbool

Posted on

Why Functions Are Better Than Classes in React.js

In the ever-evolving world of web development, React.js has emerged as a powerful and popular library for building user interfaces. While React allows developers to create components using both functions and classes, the use of functions has gained prominence in recent years. In this article, we will explore why functions are considered superior to classes in React.js development. We'll provide examples and insights to illustrate why this shift in preference has occurred.

Understanding the Basics

1. Functions and Classes in React.js
Before we delve into the advantages of using functions over classes, let's briefly understand the key differences between the two in the context of React.js.

1.1 Classes
Classes in React are often referred to as "class components." They are traditionally used to define components and manage their state and lifecycle. Class components extend the React.Component class and require more boilerplate code.

1.2 Functions
Function components, on the other hand, are a more concise and modern way to define React components. They are also known as "functional components." Function components are essentially JavaScript functions that return JSX elements.

Advantages of Using Functions

Now that we have a basic understanding of both functions and classes in React.js, let's explore why functions have become the preferred choice for many developers.

2. Simplicity and Readability
One of the primary reasons developers favor function components is their simplicity. Function components are more concise and easier to read compared to class components. Let's take a look at an example to illustrate this:

Class Component:

class MyComponent extends React.Component {
  render() {
    return <div>Hello, World!</div>;
  }
}
Enter fullscreen mode Exit fullscreen mode

Function Component:

function MyComponent() {
  return <div>Hello, World!</div>;
}
Enter fullscreen mode Exit fullscreen mode

As you can see, the function component requires fewer lines of code, making it more readable and less error-prone.

3. Improved Performance
Function components offer better performance than class components. This improvement is due to the introduction of React Hooks, which allow function components to manage state and side effects efficiently. Hooks, such as useStateand useEffect, have simplified state management and lifecycle operations.

4. Reusability
Function components promote reusability. They are easier to extract into smaller, reusable components, making your codebase more modular and maintainable. This reusability is essential for building scalable applications.

5. Hooks and State Management
React Hooks, introduced in React 16.8, have revolutionized the way developers handle state management in function components. With hooks, you can manage component state and lifecycle events without the need for class-based components. This not only reduces boilerplate code but also enhances code clarity.

Examples and Use Cases

Example: Creating a Counter Component
Let's create a simple counter component to demonstrate the difference between a class component and a function component:

Class Component:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    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>
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

Function Component using Hooks:

import React, { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  };

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

Enter fullscreen mode Exit fullscreen mode

In this example, the function component using hooks is more concise and easier to understand.

Conclusion
In the world of React.js development, function components have risen in popularity due to their simplicity, improved performance, reusability, and the power of React Hooks for state management. While class components still have their place, especially in legacy codebases, function components are the preferred choice for new projects and modern development practices.

Incorporating function components into your React.js projects will not only streamline your code but also make it more maintainable and adaptable to future changes.

Top comments (21)

Collapse
 
eerk profile image
eerk • Edited

Not sure if the argument "the function component requires fewer lines of code, making it more readable and less error-prone" is actually true.

Just look at stackoverflow, dev.to, and youtube to find tons of questions and contradicting explanations of the useEffect hook. When to use it, where to place it, do you need useMemo or useCallback, "You are using useEffect wrong", etc. etc. etc.

Collapse
 
brense profile image
Rense Bakker

In all fairness, that's actually the fault of class components and not hooks 😜 people got confused because someone somewhere tried to apply class components lifecycle method logic to the useEffect hook and it all went downhill from there. The confusion about useMemo mostly stems from people who have not realized the difference between passing props by reference or by value and not realizing how many bugs you can introduce if you pass a prop by value 😛 I was hoping that misconception would die quickly, after people started realizing how bug prone their React code got when they did it wrong, but what they did instead was blame it on the useEffect hook because that's where the symptoms of bad state management would start to show 😛

Collapse
 
eerk profile image
eerk

"I was hoping that misconception would die quickly" - the same has been said bout usage of the "this" keyword in a class. People just find it confusing because it is not intuitive.

Thread Thread
 
cg_theone profile image
cg_theone

No, people find it confusing because they're amateurs and juniors, because nowadays everybody and their dog is a web developer.

Collapse
 
dsaga profile image
Dusan Petkovic

One things I can say for sure is that they are less error prone, as "this" is not used in functional components, and its easier to test (as long as you know how to mock a custom hook - its a bit tricky but not too hard)

Collapse
 
pengeszikra profile image
Peter Vivo

Even shorter, mark: it is really simple pure function, even don't have props.

const MyComponent = () => <div>Hello, World!</div>;
Enter fullscreen mode Exit fullscreen mode

Here is the better one which do some works.

const Title = ({title, ...rest}) => <h1 {...rest}>{title}</h1>;
Enter fullscreen mode Exit fullscreen mode

When we start using childrens, hooks, our functional compontents start more and more complicated. Hooks just a kind of replacer of class innerstate capability.
But even the real complex one is looks like:

const Complex = (props) => {
  const stateAndActions = useSomeHook(props);
  switch (innerState.case) {
     case CASE.ALPHA: return <Alpha {...stateAndActions} />
     case CASE.BETA: return <Beta {...stateAndActions} />
     // ... so on 
     default: return <Default {...stateAndActions} />
  }
}
Enter fullscreen mode Exit fullscreen mode

Or using some Context to avoide prop drilling.

Collapse
 
georgewl profile image
George WL

And of course, custom hooks, to encapsulate reusable logic

Collapse
 
codewithmhd profile image
Codewith-Mhd

I am a front End Developer I have been working with react js since 2021 and much more I wrote a functional component. in my code because it is simple and easier than class components and reusable in everywhere which we needed we can reuse. (React Js is Perfect)

Collapse
 
ncpa0cpl profile image
ncpa0cpl

I find it hard to believe that functional components have better performance than class components. Everything I know about JavaScript would suggest otherwise.

A class component doesn't redeclare new functions, dependency arrays and other garbage on every render cycle. Allocating new memory for those things is not free, and increases the amount of time the Garbage collector will have to spend cleaning all that up. useCallback is also not necessary in class components, so react doesn't need to diff the dependencies every single time. Also diffing props manually in one of the lifecycle callbacks is going to be faster than doing so dynamically via dependency arrays since you don't have to iterate over it.

The claims in the article about hooks enabling react to "manage state and side effects efficiently" doesn't make much sense to me either. How exactly is it more efficient? Sounds like a bunch of bs.

Collapse
 
nevcos profile image
Filipe Costa

Great answer 👌 I think exactly the same.

Collapse
 
dsaga profile image
Dusan Petkovic

I wonder why exactly do functional components offer better performance than functional?

I believe they probably do, but I wonder if its just a consequence of developing in a functional way or something under the hood is more performant in hooks vs legacy, and what exactly?

Collapse
 
oculus42 profile image
Samuel Rouse

A pure functional component is guaranteed to produce a consistent output for a given input and has no internal representation of state that needs to be consulted or maintained. React does not spend time creating, storing, and tearing down instance when using pure functional components, it just passes them information and gets back something to put into the DOM.

I don't have actual numbers on this, but I expect the performance benefit is much smaller with hooks. Hooks removed much of the complexity of dealing with classes but it hides the instantiation and logic to "align" the hook state from each render – which is why you can't have conditional hooks

Collapse
 
dsaga profile image
Dusan Petkovic

Do you mean that there are not much performance benefits when using hooks?

"but I expect the performance benefit is much smaller with hooks. "

Also, technically its rare to have PURE components in react, or maybe some are PURE, but they can also have state with hooks or effects, maybe its less logic that react needs to do behind the scenes for class components and for functional just more re-renders are triggered...

Collapse
 
rajaerobinson profile image
Rajae Robinson

Great article!

Functional components and hooks have certainly simplified React development. No wonder they are now the standard. I wrote a helpful article explaining the concept of hooks in React.

Collapse
 
codewithmhd profile image
Codewith-Mhd

const helloWorld =()=>{
return (" hello world");
}

Collapse
 
georgewl profile image
George WL

Even bigger reason: React 17+ it's designed to be functional first.

Plain and simple

Collapse
 
antonkobelev profile image
AntonKobelev

👍 thanks!:)

Collapse
 
codewithmhd profile image
Codewith-Mhd

it's a better choice to use functional components