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!