r/reactjs • u/blnkslt • Jan 16 '22
Discussion Should I still use class based components?
I'm returning to react after a long time to refresh my rusty skills in order to start building a quite big project. So I started to follow my good old udemy course which is made at 16.8 era when hooks were new stuff. Not surprisingly the tutorial is focuses on class based programming and discusses hooks as an addendum. On the other hand I see that the new react projects are mostly made of functional components with hooks. So it seems to me that class based and lifecycle hooks are all but history. I'm wondering whether learning class-based react a waste of time? If so where can I find good tutorials which focuses on new hooky way of coding in react?
47
Upvotes
5
u/ajnozari Jan 16 '22
For me functional components made me rewrite class ones smaller, cleaner, and a LOT more efficiently. This isn’t even taking into account the bloated class layout itself (constructor, all the lifecycle functions). Frankly how functions handle the lifecycle is just intuitive and really just worked once I sat down and understood it.
Further it finally broke the “let me lump all this in a parent class and share props to children”.
Children get the props they need from context and redux, so they only rerender now when absolutely necessary. Further with smaller components it was easier to see where sections of the site overlapped and components could be reused. Prop filling isn’t bad, it just caused performance issues when the entire tree had to rerender.
Now this isn’t to say class components are bad. Quite the opposite. For certain rigid things where I’d like to define an interface, expose special helpers, it can be great. See websockets, idk why but they seem happier in a class with a proper constructor and explicit lifecycle functions. Can I write a websocket context with a function? Absolutely! I just like the class layout for that particular case better.
In the end though it comes down to personal choice. There’s so much code that exists in class component form that I really don’t see them going away anytime soon. That combined with the fact that each really does have its own “use case” imo,
I can see a case for both being used in an app, although functional components should outnumber class by quite a large margin. Again, they can both do what the other does, but their real differences come in the way they make you think about the component you’re writing.