10 ms·
I must be the only person in the world who likes class components in React. Sure, it's often overkill and a functional component does the same thing with less
by nonethewiser 4y ago
I must be the only person in the world who likes class components in React.
Sure, it's often overkill and a functional component does the same thing with less code. Use a functional component in these cases. But if you're doing something more complicated then stop treating class components like the fucking devil. They have their place.
- gwn7 4y agoYou are not alone.
- elbac 4y agoDid you use to work in Java?
- nonethewiser 4y agoNo
- goatlover 4y agoComing from Ruby and Python, I also prefer class components to hooks. I had to deal with hooks enough in Drupal/PHP which is in the process of deprecating them in favor of Symfony classes.
- nightpool 4y agoDrupal hooks have nothing to do with React hooks except sharing a name. What would cause you to compare the two?
- cooperadymas 4y agoSharing the same name, I presume.
- goatlover 4y agoDrupal hooks are a functional approach to design compared to the OOP approach of Symfony components. As in you use functions to modify/extend existing code instead of inheritance. That's the context of the discussion, not whether they are otherwise similar to React hooks. Anyway, I just tend to think more in terms of making things with classes/objects than with functions.
- bornfreddy 4y agoNo, you're not the only one. Apart from useState, which is elegant, I hate others with passion. How can a replacement for lifecycle methods be called useEffect? Seriously? Great article, couldn't agree more with them.
- phailhaus 4y ago> How can a replacement for lifecycle methods be called useEffect? Seriously? Yes, seriously. Have you used it for more complex components? You can split your effects across multiple useEffects, and have a guarantee that they run completely independently of each other (especially since you know what their dependencies are). Compare that to lifecycle methods: you only have one per component. All your effects concerned with setup have to be piled into the same function, and their associated teardowns have to be elsewhere in another method. How do you audit a behavior's logic? How do you reuse that behavior in another component? It's not easy, and you can cause weird bugs depending on the order in which you run them. Compare that to useEffect. Setup and teardown in the same function, which allows it to focus on just one behavior. And if you need to, it can be trivially pulled out into its own hook and reused across all your components.
- bornfreddy 4y agoFair enough. Though, the first question is - why does the component do so many things? Do they all need to be in a single component or can you break them apart? For the cases when this is not possible, I agree, useEffect works better than classes lifecycle methods. But do you really want a system which caters to a small percent of use-cases at the expense of readability in others? And the improvement, to my eyes, is not that big anyway. The hooks are my main gripe with React, but as the OP, I don't see a better alternative either - at least not one that would be worth a rewrite.
- phailhaus 4y agoIt's not a matter of doing too many things. Lifecycle methods exist to be used, and the moment you have any behavior that requires multiple lifecycle hooks, you will run into these issues. So I'd say it's not a small-percentage of use-cases at all, and you'll often see the benefits of hooks immediately.
- phailhaus 4y ago> They have their place. How so? There is nothing that a class-based component can do that a hook-based component can't (EDIT: Except for error boundaries). I'd go as far as to say class-based components are strictly inferior because they force you split your behavior logic across lifecycle methods and are not easily composable. I've been able to support much more complex behavior easily with hooks (e.g., connection management), that would have been a nightmare with class-based components.
- tshaddox 4y agoYou still need to use class components for error boundaries. https://reactjs.org/docs/error-boundaries.html https://reactjs.org/docs/error-boundaries.html
- ajkjk 4y agoYeah, this feels like a weird oversight.
- tshaddox 4y agoA bit weird, although it’s not clear how they would do it without class components. I guess it would probably look something like React.forwardRef.
- ajkjk 4y agoThey could provide a <ErrorBoundary> component as a built-in that just does what the current one does, but is implemented by the library.
- k__ 4y agoIsn't it also easier to get subtle lifecycle bugs with them, because you can forget one.
- phailhaus 4y ago
- kayson 4y agoI'm definitely a novice when it comes to React, but I've shipped a beta version of an internal took using it. I never understood the emphasis on functional components. Everything I did using them was made more complicated and less obvious, especially for colleagues who are not familiar with React or JS in general. React is built on components which are objects (both in a programming and GUI sense). Using OOP to describe them just makes so much more sense to me.
- mikeryan 4y agoFunctional components tend to be easier to compose. If your class component has very specific functionality that you won't need in other components it's fine but if you want functionality that will be shared across multiple components wrapping up that code into it's own hook is easier to share across components then trying to use wrappers, extending classes and HOCs.
- kayson 4y agoCan you give me an example? I didn't have that experience. I extended classes for everything and it was super easy. But as I said, I was probably using react in a fairly basic way.
- mikeryan 4y agoFor example you have a button that you want to add a hover effect to. So it's got "onMouseEnter" and "onMouseLeave" handlers that sets a "hovered" state variable to true/false. If you have that functionality in a class component, and want to share it with a new link component, then the React Class way is to create a "withHover" HOC and wrap your link component in it. withHover(LinkComponent) which will have the necessary variables and pass them as props to your LinkComponent which is "okay". But what if you have like 5 of these little hooks? Your LinkComponent now needs to be wrapped in each (or them all wrapped into a single HOC) and has to accept the props for all of them. Or, if you're extending classes as you describe you now have class LinkComponent extends HoverClass, ClickClass, DataClass etc... With functional components you have something like a "useHover" hook. It passes back the hover state and the "onMouseEnter" and "onMouseLeave" callbacks necessary for your link within the functional component itself. It doesn't have to expose props to it's HOC, so it's now self contained. It seems the philosophy of react is to have a lot of "littler" discreet pieces of code be they components or hooks and not have to have a ton of dependencies between them. You tend to get better tests this way as well as it should make it easier for other devs as they don't have to know the whole system and can work on a more discreet bit. I, personally, use function components pretty much exclusively these days. If the function gets too big with hooks I tend to just create a single hook from them, not because it's going to be shared but just to keep my code more manageable, the hooks create props and the components consume them. To each their own. I don't seem to be frustrated by the problems many in this thread and the article share.
- yamtaddle 4y agoNope, I'm with you. React inventing a half-baked, partial re-implementation of objects/classes (in a language that already has them!) with super-weird declaration syntax & runtime behavior, just to avoid telling their userbase "Ok you will have to use classes sometimes, for certain functionality", was when I started looking around, because they were clearly out of real problems to solve that were sufficiently good-looking-on-a-résumé, and it was just gonna go downhill from there. Class components were/are just fine.
- narrator 4y agoThe cycle of javascript libraries: * SHOW HN: UberTinyUltra.js Here's my new super light-weight 4k Javascript Library! * How I switched to UberTinyUltra.js from PopularFramework.js and simplified my life! * SuperCoolStartup switches to UberTinyUltra.js * How I built my unicorn on UberTinyUltra.js * UberTinyUltra.js 2.0 now with a compiler, classes, typesafety and a C++ like turing complete template language to take on the big enterprise jobs because we have too much time, attracted a lot of developers to the project, and ran out of obvious simple features to implement! * I hate you UberTinyUltra.js you are too complicated. * ShowHN: SuperTinyMega.js Here's my new super light-weight 4k Javascript Library!
- datavirtue 4y agoOften, things don't get bloated because the developers are bored, it stems from users requesting features because they are doing it wrong. Sort of how AWS keeps mucking with Lambdas so that thier customers can keep doing it wrong and paying too much. Or how doctors just give patients scips if they ask about a drug and it won't incur them any liability. Over and over I have seen the world shout the praises of a new paradigm that solves a problem...except they totally misunderstand the concept and run in an unintended direction. No one can fight that momentum. So they don't. It happens with nearly everything in tech.
- dntrkv 4y agoReact is coming up on 10 years since its release. That world you describe is far from reality nowadays.
- jwlake 4y agoI use functional components only for things without state. If anything has state I use class components because otherwise you go mad. ;)
- wpietri 4y agoCould you say more about this? I'm not a React user, but to me one of the OO fundamentals is "object = behavior + state". What you're saying sounds so obviously correct to me that I guess there's something pretty weird going on in React-land?
- yamtaddle 4y agoReact added "hooks" which are basically methods and properties implemented as FIFO queues instead of lookup tables, with terrible syntax that requires you to declare them inside their constructor (the "functional" component's... well, function). No, I'm not kidding. Unless something's fundamentally changed about the code since release, they even end up attached to an object representing the UI component, by the time the heart of React's runtime code considers them. It's some real Rube-Goldberg shit. I read the code because I read the announcement docs and was like "wait, it looks like they... but no, surely they didn't" but yeah, turns out, they did.
- nobleach 4y agoWhat's worse, they have interesting "rules" that one really needs to use a linter so their IDE/Text editor gives them friendly reminders. One cannot conditionally call useEffect. One needs to add all dependencies to useEffect's dependency array - BUT that has potential to cause infinite re-renders (especially when using a getter/setter pattern with useState). They encourage DEFINING functions inside of other functions. Years of CS education and practice go right out the window because some popular JS person on Twitter says, "it's fine". When pressed about it, be ready to be hit with, "You don't understand hooks".
- skydhash 4y ago
- BilalBudhani 4y agoI ditched React soon after they released hooks, mainly because I couldn't relate to the tradeoff React roadmap was taking from there. They went in a different direction from that point onwards, it seem like whatever code you write will become obsolete with the new set of best practices in the next release cycle. More importantly, I realized React is trying to tame Facebook level of problems and hence their design decision steams from those data points. I develop small/medium type of frontend apps which doesn't need to apply solutions developed for such a scale. These days I'm using Hotwire[1] (Turbo + Stimulus) with fair amount of vanilla javascript libraries in my apps. Occasionally, when I need to develop a reactive piece of UI I reach out for Svelte[2] I'm quite happy after making the move. My apps complexity has reduced drastically and there is huge boost in my overall productivity. [1] https://hotwired.dev https://hotwired.dev [2] https://svelte.dev https://svelte.dev
- todotask 4y agoI haven't got the ideas why many frontend jobs require experience in React whether it's for a new or existing projects, maybe I need enlightenment.
- mym1990 4y agoProbably because a large portion of their app is built in React?
- pas 4y agoBecause HR (and IT strategy) nowadays is a farce, managers, decision-makers and the actual organizational units that do hiring rarely have the necessary systemic big-picture knowledge/information, foresight, experience, longitudinal thinking that would allow them to venture out of their preset suboptimal ways.
- dntrkv 4y agoAre you suggesting that requiring React experience for a job where you will use React is not a reasonable ask?
- pier25 4y agoI totally agree. I actually stopped using React around the time hooks were announced. In retrospect it's still not clear if hooks were even a good idea. Changing the core methodology of a project used by millions of developers at the time was extremely irresponsible. They basically made obsolete all React educational resources overnight. I'm sure people making money by producing React educational content were very happy about that though.
- cdelsolar 4y agoI keep seeing this sentiment here but as someone who’s used both the old paradigms and hooks - hooks are much better and simpler overall.
- uptown 4y agoYour argument is very compelling. /s
- WHATDOESIT 4y agoThere was no way to make async rendering possible with classes. It was necessary and they spent a lot of time trying different approaches that'd continue the old paradigm, but it couldn't be done.
- pier25 4y agoMaybe, but would you need async rendering if React wasn't so slow?
- WHATDOESIT 4y agoAs opposed to what? Vue is slower and Angular too. Perhaps Svelte might be faster but the programming paradigm is a little weird. Writing pure JS is bullshit - I tried it few months ago and even a very simple app - for public transport schedules - got very unmanageable very quickly. I'm currently working on a project with hundreds of reactive components shown at any given time (very extensive financial analytics/modeling collected from over 500 data sources and real-time updated). Async rendering is a godsend. Perhaps React isn't for you if you don't see the need.
- reactspa 4y agoIs it possible to continue coding in some early version of React that only had class components? Has anyone branched that into its own thing yet?
- ncann 4y agoClass component is still fully working as of latest React and won't be going away (at least according to the React docs). The main issue is when you work on a codebase that's full of function components and hooks it's hard to mix in class components.
- reactspa 4y agoI really liked the old model where Class Components were used when there was state, and function components were used when there was no state. Hooks have always seemed so weird. And turns out it's the same for many others.
- rileyphone 4y agoI think the problem is ES6 classes just aren't very flexible or expressive, compared to systems like Ruby, Smalltalk, or CLOS. For a lot of programmers, half-assed classes are worse than no classes, even when they can help with organizing state and behavior.
- pjmlp 4y agoThey are as expressive as SELF, maybe time to learn how to use them?
- rileyphone 4y agoJavascript's prototypes are more expressive than its classes, but still come short of Self on a few levels: 1. Self's prototypes support multiple delegation while JS objects only have one prototype (can be fixed with Proxies). 2. Javascript objects lack a universal clone method. 3. Self is entirely message based, while JS is property based.
- lmm 4y agoThis is backwards. Even in ES6, classes already too flexible and expressive: they allow you to express a bunch of things that don't make sense.
- 3vidence 4y agoI overall agree. I use functional style programming a lot but for some reason hooks have always confused me. The component classes generally make sense to me and map onto other paradigms like flutter, vue, etc. Sure methods like componentDidMount are a mouthful but I found it much more explicit
- programmarchy 4y agoIn my view, hooks are more about managing state dependencies, rather than functional programming, per se. So they're more useful for simplifying methods like componentDidUpdate, rather than componentDidMount. When you need to detect changes by comparing prevProps to this.props or prevState to this.state, the logic can quickly get really ugly. Instead you can just put the relevant prop or state you want to monitor in the dependency list of a hook, and it will be triggered whenever that dependency list changes.
- zumu 4y agoClass components are great. One thing I did see at my old job, however, was people extending the class components, sometimes 10+ times, which was very unexpected and harder to reason about. With functional components and hooks, you enforce proper composition.
- neals 4y agoI think many of us are still using class components and loving it. We're just not that vocal because we're busy get stuff done.
- alexfrydl 4y agoIt really rather seems like they achieved a near-perfect library for creating complex web applications, then in order to justify continued work on the project, simply kept making up unnecessary clever/cool features motivated by vibes that classes are passé.
- avereveard 4y agome too use effect is too hard to track for anything but the trivial cases, class components are a good midway between being able to understand the program in 3 years and not having to manage one own state<>view mapping
- xaferel 4y agoI totally agree with you and you are not alone for certain.
- gherkinnn 4y agoThey absolutely do not have their place. Just about everything is worse with class components. I’ll take a dozen useEffects over a single class component any day. That said, the hooks model is far from perfect. They give you a lot of rope to hang yourself with and were badly introduced. Within weeks the internet was ablaze with terrible advice. When so many people get it wrong, the library is to blame. And I wish hooks were as robust as Solid.js’ signals model.
- mmis1000 4y agoI don't think hook themselves are a bad thing. But the way react implements hook probably is. The react team invented their hook format the suite themselves the most, but that probably isn't for other. Vue 3 also has hook now. But none of these defects in the article exist. In vue. To use some value in a effect, you just use it and it is tracked. If you need to clear up your code. You cut some code into a useXxx function, and your reusable utility is done. You can use it everywhere now. You don't really need to specify dependency of whatever by yourself. If you must manipulate a dom, you just manipulate it. It will work as long as you revert the change before vue want to update it again.(And vue do provide a hook for you to attach a handler when these happen) These restrictions are added by the way react implements hook, but not hook themselves. Hooks are just more user friendly services (by allow the hook to attach to component instance without all the glue codes(addListener or whatever))
- gherkinnn 4y agoVue 1.x was great, v2 lost its way, and Vue 3 with the composition API looks fantastic on paper. (I haven’t used it in any meaningful way) I’m even more impressed with the extended Vue ecosystem like Vite, Vitest.
- mmis1000 4y agoI used it in a few project. And it reduces the code by a lot. For example. To make a mutex to prevent duplicate submit of form. You use need to declare a instance field and wraps the code that do the submit. That alone is 3 lines of code but don't even include error handling. But now I sealed it into a one line hook const wrap = useMutex() const submit = wrap(async () = { … }) And then the submit can't run in parallel now.
- ericmcer 4y agoHooks are a natural progression from class components, class components seem more straightforward with all the willMount beforeMount etc. but they trick you into visualizing your component in different states of mounted/rendered/etc. That goes against what React wants to be at its core, which is totally immutable and pure, it isn't mounted or pre/post-render it looks the same whether it is the first render or the 100th. Ultimately I think the mental model of the component as a pure function is superior to juggling the react lifecycle.
- deleted 4y ago[deleted]
- deleted 4y ago[deleted]
- lofatdairy 4y agoClass components were/are fantastic for training new devs because of how easily abstracted the mental model is compared to memorizing all the hooks and their use cases. Obviously, the syntax tends to be a bit more verbose in general, and I won't deny that hooks making improving performance easier, but at the end of the day I prefer code that's readable whether it was written yesterday or 5 years ago - even if it costs like 20 more lines of boilerplate. I also think the fear of verbosity in this post is why I can't take it too seriously. Solo maintaining a not-so-old Expo application which uses React Navigation, I constantly have to rewrite large sections of code due to constant refactorings to match whatever coding style is hot at the moment, as the 6 month deprecation deadline is constantly at my doorstep because I have bigger fish on my plate. SO answers being out of date isn't a problem because React is too old, it's a problem because of everyone wanting it to be shiny and new again, and React acquiescing to those demands. The author does have a bit of a point with libraries, but I counter with Nessim Btesh's fantastic article regarding proper React style[^1]. In short, you shouldn't really be depending on libraries for production needs, just for prototyping. [^1]: https://nesbtesh.medium.com/how-i-write-react-after-8-years-12cbf82c351 https://nesbtesh.medium.com/how-i-write-react-after-8-years-...
- jasongi 4y agoYou aren’t the only person, I’ve certainly heard it before. But I’m yet to hear a convincing rebuttal to Mixins Considered Harmful [1], the hooks talk [2] or the Motivation section [3] on the announcement. The arguments I’ve heard is that it is “cleaner”, “more understandable” or the OO style is preferred. Some developers feel uncomfortable with hook magic because it introduces a more niche programming concept than OO (e.g stateful functions). I don’t find these arguments compelling. What the React team managed to do was reproduce the same functionality as class components while decreasing the footguns associated with them. 1. https://reactjs.org/blog/2016/07/13/mixins-considered-harmful.html https://reactjs.org/blog/2016/07/13/mixins-considered-harmfu... 2. https://youtu.be/dpw9EHDh2bM https://youtu.be/dpw9EHDh2bM 3. https://reactjs.org/docs/hooks-intro.html#motivation https://reactjs.org/docs/hooks-intro.html#motivation
- chrisza4 4y agoI think there is more footgun in the hooks, especially rules of hooks. I worked with Junior dev and I can see unexperienced dev misused hooks more often than lifecycle.
- edgyquant 4y agoI used to be the same when I switched jobs and had to start doing functional. I now disagree that there are ever instances a class is needed. You can use hooks to encapsulate and reuse state, contexts, etc
- mclightning 4y agoI am in the same boat. I miss class components so much, but because of the trend it is hard to fight for it. It is just so verbose and easier to read. It is more in line with the majority of graphics/ui frameworks in the whole software engineering ecosystem. It reminds me of render loop in many game engines, along with special event triggers (mount, unmount etc.). It makes me feel like an actual programmer, rather than a "view orchestrator"...
- dh2424 4y agoI totally agree. I just joined a shop that has banned new class components from entering the codebase and I still don't understand why.
- phendrenad2 4y agoWell, unfortunately treating hooks like they're the worst thing since the devil is just the latest (and most humorous) in a long trend wherein a new syntax is added to something, and every developer thinks "okay, the preexisting alternative is now old and bad". I've been scolded many times in code reviews for absent-mindedly making a class-based component instead of using hooks (mind you, this was a legacy codebase FULL of class-based components. Are react developers just undereducated? Considering how many developers I've seen spend MONTHS "learning hooks" I think so. (Not to mention, every single React project I've been on in the last 7 years has been me and some developer who's never used React before, but has a lot of shallow blogpost-driven opinions).
- cdeutsch 4y agoI'm with you. I much prefer class components. So much easier to understand and work with. I disliked hooks after first trying them on their release, and I hate them now. I'm still bitter that a senior engineer didn't step in and prevent them from destroying the react ecosystem. I wonder if they were have been squashed if React was developed outside Facebook?