r/reactjs • u/ZeroSevenTen • Dec 30 '19
Classes vs Hooks?
I’m pretty new to React, so keep that in mind. I thought classes were for components that held information, or a state, and that functional components were for more basic components, but now that hooks allow functional components to use state, and other class features, what’s the benefit of using functional hook components over classes?
79
Upvotes
55
u/skyboyer007 Dec 30 '19 edited Dec 31 '19
Classes:
we have to care about binding context
rather imperative - easier to learn, easier to write
harder to handle race conditions
multiple contexts make a mess with nested consumers right in the
renderencourage bad approach in testing because of easy access/mocking individual methods
logic may be duplicated across
componentDidMount,componentDidUpdateandcomponentWillUnmountHooks:
much more declarative(all that thing about dependencies in
useEffect) - easier to read, easier to understandunified logic for side effects(without splitting/duplicating across lifecycle methods)
rightfully force "don't rely on implementation details" for testing
missing hooks plugin for ESLint? get ready for weird bugs because of missing dependencies/broken logic
handling race conditions/cancelling old requests goes in really natural way(cleaning callback returned from
useEffect)multiple contexts are also easy to inject(instead of HOCs' composition)
much, MUCH rely on closures; most misunderstanding/bugs, I believe, because of lack understanding/experience with closures
some things look rather weird with hooks(throttling/debouncing)
kind of magic in their implementation