Is there any particular criteria to prefer class components vs functional components?
I've read many threads arguing about this, in many cases discouraging the use of ES6 classes in general (google "Eric Elliot class"). At least for me is a bit troubling since there are a lot of examples and documentation written using classes.
I have experienced some of the pitfalls of using class in other contexts outside React, although I do not discard these problems being a result of amateur coding skills on my part. Yet similar experiences are shared by more experienced developers.
I would like to hear your thoughts about this, and what is the position of the React team on this topic.
EDIT: Reading below I see that you already answered a very similar question, anyway I leave this one in case there is anything else you would like to add. Apologies!
The one thing I encourage you to avoid is inheritance hierarchies. I think classes are okay as a form of organizing code, but work really poorly as a way to reuse the implementation through inheritance. I wrote about this here.
If you just inherit from React.Component or React.PureComponent there’s nothing wrong about using classes. Certainly, they can be unnecessary if your component doesn’t have any state or lifecycle. In this case a functional component would use a tiny bit less memory. However, it is annoying to convert them back and forth when you want to add state and/or lifecycles later 🙂. So that’s really up to you—it doesn’t matter that much either way.
TLDR: don’t create your own React base component classes and hierarchies.
One notable difference between functional components and class components is that refs (references to underlying DOM elements) can't be used with functional components - has forced me to use a class a few times, even when the component has no state/lifecycle.
A small price to pay for a great library - awesome work Dan!
We're a place where coders share, stay up-to-date and grow their careers.
We strive for transparency and don't collect excess data.