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.

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!
Dilshan is a blogger and self-taught web developer currently based in Vienna, Austria. He is always on the lookout for new opportunities and can be reached through his website or Chunk Bytes.
Be First to Comment