DEV Community

Discussion on: React: class components vs function components

Collapse
 
bradwestfall profile image
Brad Westfall

The issue with class based components and the driving reason why the React team went towards functional components was for better abstractions. In 2013 when React came out, there was a feature called mixins (this is before JavaScript classes were possible). Mixins were a way to share code between components but fostered a lot of problems and anti-patterns. In 2015 JS got classes and 2016 React moved towards real class-based components. Everyone was excited that mixins were gone but we also lost a primitive way to share code in React. Without React offering a way to share code, the community turned towards patterns instead.

With classes, if you want to share reusable code between two components, you only really have two pattern choices - higher order components (HoC's) or the "render props" pattern. HoC has several known problems. In other words, I could give you a "try to abstract this" task with classes and you just wouldn't be able to do it with HoC, it had pretty bad limitations. The render props patter was popularized later and it actually fixed all four known issues with HoC's, so a lot of react devs became a fan of this new pattern, but it had new new problems that HoC's never had. I wrote a detailed piece on this a while back gist.github.com/bradwestfall/4fa68...

The reason why hooks were created was to bring functional components up to speed with class based components as far as capability (as you mentioned above) but the end goal of that was custom hooks. With a custom hook we get functional composition capabilities and this solves all six issues of Hoc and Render Props problems, although there are still some good reasons to use render props in certain situations (checkout Formik). If you want, checkout Ryan's keynote at the conference where they announced hooks youtube.com/watch?v=wXLf18DsV-I

Also, the reason why classes are still around is just because the React team knew it would be a while for companies to migrate their big code bases from classes to hooks so they kept both ways around.

Hope it helps someone

Collapse
 
colocodes profile image
Damian Demasi

Wow, thanks so much @bradwestfall ! This is a very interesting back-story on classes and function components. I really appreciate the time you took to explain all of this.

Collapse
 
bradwestfall profile image
Brad Westfall

No problem, your article does a nice job comparing strictly from a syntax standpoint, there's just the whole code abstraction part to consider. Honestly, after teaching hooks now for 3 years, I know that hooks syntax can be harder to grasp than the class syntax, but I also know that most developers are willing to take on the more difficult hooks syntax for the tradeoff of having much better abstraction options, that's really the main idea. For real though, checkout Ryan's conference talk, it's fantastic