Skip to content

Functional Or Class Components In React

Components are the bread and butter of React, or any modern JavaScript framework for that matter. Components here, components there, components everywhere! ðŸĪŠ If you’ve spent any time using React, you may know that there are two types at your disposal: Functional and Class components. And perhaps you may even be confused as to when you should use them. Well, buckle your seat belts, boys and girls… you’re in for a (very) quick explanatory ride.

A thing of the past

Here’s the deal: you should not use Class components in React anymore! 🙅‍♂ïļ For all intents and purposes, Functional components are identical to its older counterpart in terms of functionality. Furthermore, there are more benefits from using them, such as:

  • Faster compilation and smaller compiled code size
  • Easier to test
  • Less verbose

However, this wasn’t always the case. It was only with the introduction of React Hooks that Functional components became that powerful. This naturally begs the question: Are Class components obsolete? ðŸĪ” Well, no(t yet)… They’re still in the library for backward compatibility, but that doesn’t mean you should still use them. Nevertheless, you will encounter a few scenarios where you will use them.

Meme about Facebook deprecating Class components in React with Functional components around
One day… ðŸ˜Ĩ

When to use Class components

So in which cases might you be compelled to use a Class component?

First, while powerful, the hook useEffect cannot completely emulate all lifecycle methods found in a class component, such as getDerivedStateFromProps. However, these methods are rarely used to begin with and can even be replicated with some custom code on top of hooks. If you’re a fan of Error Boundaries, you will unfortunately still have to opt for a Class component.

Second, you may be working with an older React version where hooks are not available yet. Not much you can do there… ðŸĪ·â€â™€ïļ Likewise, it applies to older React libraries. Or even, it could be you’re working on a Class component and have decided not to refactor it into a functional component due to its complexity (or your laziness! 😂).

Third…. use a Functional components whenever possible!


Did you find what you came for? Hopefully you know now when to use Functional and Class components in React. Want me to cover something else? Let me know in the comments below! Share, if you liked this post!

Published inReact

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *