8 ms·
React hooks solve a problem most people don't have. Classes worked fine in 99% cases and have the nice benefit of encapsulating any side effects. Hooks make it
by jameslk 8y ago
React hooks solve a problem most people don't have. Classes worked fine in 99% cases and have the nice benefit of encapsulating any side effects. Hooks make it easy to hide side effects and dependence on state (think global variables) by letting developers hide these things several layers deep in functions that may get called by components. This is a footgun waiting to go off.
If you need to use state or side effects, just use classes. Most of the time all you need is pure components with fewer stateful components above controlling the pure components. Pass down your state and state modifiers through explicit and easy to follow props (or use a state management system if you find yourself prop drilling). If you're using state and side effects everywhere, you're probably not using React correctly.
- rajangdavis 8y agoWhen do you actually need to use hooks? I saw a nice visual where hooks ended up reducing code, but I am not sure I grok it.
- snek 8y agoWhen you want to work with state in a component (so most of the time) but are too stubborn to admit FP isn't the right choice for the job
- jameslk 8y agoThis is my feeling too to be honest. I think hooks are very misguided. Unfortunately it's no longer FP anymore when your "referential transparency" has been completely blown away.
- jordanwallwork 8y agoFP?
- jameslk 8y agoFunctional Programming
- jameslk 8y agoI've been using React in projects large and small for years and I can remember VERY FEW situations where I said to myself "gee I wish I could bundle a bunch of state or side effects together and share it between components like React mixins of lore". If you can't think of a situation where you need it, that's probably because you don't. Anything plain old JavaScript class components can't handle here were solved by using HOCs/render prop patterns or React context (often in the form of state management libraries such as Redux).
- deleted 8y ago[deleted]
- sorahn 8y ago> HOCs/render prop Both of these inflate the VDOM, and present themselves as a false hierarchy that your app requires. HOCs artificially inflate the props that any component requires, and it's harder to see what props you're actually supposed to pass to the component, vs the ones that should come from a HOC. Hooks remove a lot of these anti-patterns.
- ng12 8y agoFor me the problem hook solves is the heartache pain I feel when I have to convert a SFC to a React.Component. Adding useState and useEffect feels much more natural. I don't think it's any more or less bug-prone than React.Component, especially because you have to be careful about making sure componentDidMount() and componentDidUpdate() are in sync.
- snek 8y agobut you introduce the danger of relying on an api that determines your state based on the order of function calls. if you accidentally take an api that pretends to work based on call site and use it in a loop or callback everything falls apart.
- littlecranky67 8y agoOnly the order of the hook function calls is tracked. The "danger" of 3rd party APIs is a theoretical one, as in most cases you would not put hook function anywhere else except the first level inside the functional component - not into callbacks or whatnot of 3rd party libraries.
- sorahn 8y agoIt only relies on that order between renders. It’s really a non issue. I just spend the last month building a new chunk of our app in hooks to try them out, and it’s really nice to be able to wrap up shared stateful logic without HoCs. A bunch of the HoCs in this app take a “propKey” param, because the HoCs are all stacked on top of each other, and prop collisions happened frequently. Also, it’s a gigantic pain to use TypeScript and “compose”.
- williamdclt 8y agoit’s really nice to be able to wrap up shared stateful logic without HoCs agreed. I loved HOCs for the composibility, abused them and very rarely encountered prop collision, but TS (or Flow) made them a massive pain
- tlrobinson 8y ago
- anonytrary 8y agoReact hooks are just a fancy (perhaps unnecessary) way of getting people to embrace closures, which help you avoid other common footguns when dealing with temporal data. If you understand closures and you know how to use them to "remember environments", then React hooks are little more than tools for concision.
- boomlinde 8y agoOther than e.g. useEffect returning a function that closes around something within, I don't see what hooks have to do with closures.
- anonytrary 8y agoYou don't need hooks to do any of this, but hooks have everything to do with closures. Hooks are created every single render, unconditionally, guaranteeing that each hook is one-to-one with the render environment that created it. The point of using hooks is that you are always referencing the props and state at the time of creating the hook and not at the time of running the hook. In this way, hooks become part of your rendered output.
- boomlinde 8y agoI know how hooks work, but what you describe has nothing to do with closures.
- hazza1 8y agoHooks solve some problems nicely, the main killer for me is that they don't work with classes, so you end up with 2 wildly different paradigms in your codebase. Feels like hooks should have been a clean start in a new framework rather than retrofitted into React.
- boomlinde 8y agoI have a hard time grasping this concern. How your codebase ends up depends on how you set it up. The introduction of hooks doesn't magically replace half of your class components with functions using hooks. You can introduce them when and how you want to introduce them. On the other hand, people who are fine with having state managed both via class components and via hooks (and why shouldn't they be?) can gradually introduce the concept and refactor existing components as needed, if and when they see some advantage in using hooks at all. If you don't want milk with your coffee, it's not a problem that there's a pitcher of milk at the table.
- hazza1 8y agoCustom hooks encapsulate logic so you can no longer use it in all of your app
- _betty_ 8y agoThis small library [1] let's you use hooks in classes. Probably has some bugs but may be good for a transition period https://github.com/kesne/with-react-hooks https://github.com/kesne/with-react-hooks
- wereHamster 8y agoHooks solve the problem that state in classes is not compositional. If you have a stateful class that manages two or more bits of state, it's a lot of work to move one bit to a different component: if not already you have to make the other component stateful, move code over there, check that all the lifecycle methods are updated etc. With hooks you can copy&paste one or two lines of code to another component and be done. I agree that the bulk of your application state should be managed centrally. But I often need small bits of state all over the place, not related to the overall app state but for UX purposes. For those cases hooks are much more pleasant to use that writing stateful classes.
- jameslk 8y ago> it's a lot of work It should be a lot of work. There should be a penalty for this. State makes your code harder to reason about and should be avoided (i.e. contained) as much as possible. > But I often need small bits of state all over the place If you need small bits of state all over the place you may need to rethink things or use a state management system. The spirit of React hooks might be to make things easier for certain edge cases but instead they will be abused by those who don't understand them to make their code harder to understand. Trust me, I've already started running into this with those who decided to cargo cult React hooks.
- littlecranky67 8y agoWhile it is true that you should not overuse state, it is almost impossible in real-world applications not to have it. I.e. a single UI toggle that shows/hides some content requires a field on the components state. Putting this in the props or even a state management container like redux would be overkill.
- jameslk 8y agoI have built real world applications with React (consumer, insurance, B2B, I work at Facebook using React currently). I've handled some pretty crazy edge cases. I've never felt I needed something like hooks. The example you gave me sounds just fine for a "smart/dumb" component pattern[0]. If you need something between props and redux, there's plenty of existing options that work fine. React context and the render props pattern come to mind. 0. https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0 https://medium.com/@dan_abramov/smart-and-dumb-components-7c... (The author of this blog post pushes hooks now yet the pattern works well in most cases)
- tanilama 8y agoI feel the same way. And how isn't Hooks are worse off in terms of testability? I have got into too far with it, but it seems to favor small piece of ad-hoc code over classes, which seems neet from the surface, but doesn't feel very encouraging towards tests coverage. Anyone that applies Hooks to production project can share your experience so far? Would love to see some real world adaptation success stories before making the move.
- boomlinde 8y ago> it seems to favor small piece of ad-hoc code over classes I think that it's important to realize is that classes aren't the only alternative to small pieces of ad-hoc code. Hooks are composable via functions. If you need to reuse your stateful behavior and side effects you can factor them into functions, and if you don't, you'll have exactly the same problems with classes.
- cageface 8y agoI've had way more random problems from not binding class members correctly than I have with useEffect. Hooks have allowed me to rip out a bunch of JS class boilerplate and my code is cleaner and easier to read as a result.
- korm 8y agoAre you against using Babel and the class properties proposal? Binding members shouldn't have been a problem in your codebase in recent years.
- cageface 8y agoI use Typescript. I'm not interested in adding another processing/parsing tool to the stack I already have. Hooks are a much more elegant solution to state management than classes, IMO, but it will probably take some time for best practices to emerge, just as they did for classes.
- paperpunk 8y agoTypeScript already supports those 'class properties' - and with a few extra features - so you don't need to use Babel for this syntax: you already have it. I'd still rather use hooks though :)
- littlecranky67 8y agoWhen you use TypeScript with React (and want sound typings per policy so any type erasures/widenings are considered bad practice) Hooks are a big leap forward. Typing classes was much to verbose, and the type system of TypeScript to this day is not a perfect fit to type class-based components. Hooks solve this problem - probably unintentionaly. Example: With Hooks you almost never need to explicitly type the type of state of a component, as whatever you pass to useState() will auto-infer the type. While when using class-based Components, you'd have to specify the state type as a generic argument; you'd have to manually specify it when you set a state using this.setState() as partial types were allowed due to reacts auto-merging of the passed argument to the state. And you'd have to use some kind of Partial<State> type when assigning only some values of the state in the property constructor. Similar issues exist when using the static defaultProps field in TypeScript - the type couldn't be inferred from the generic class argument, as a Partial<Props> type is valid for the defaultProps field. As a result, the defaultProps (as well as the default state property) is cast as the empty object type {} by default if you don't explicitly assign a type - which makes you lose basically all the type information because every object is assignable to {} in TS. And if you ever tried to strictly type your HOCs or renderProps you know how hard it was, sometimes utilizing the conditional/mapped generic types feature of TS. This is completely gone with Hook. I could go on telling how stupid it is when you disable nullable types in TS (strict mode) because TS will not let you use any non-nullable prop inside of render() - even if that prop is initialized in the static defaultProps field. You'd have to override the non-null check using TS exclamation point operator. This is also gone with Hooks. I don't know if they designed the Hooks API with TS in mind or if this is completely accidental, but if you migrate a TS project with strict mode enabled to Hooks, you will see how much implicit type annotations can be dropped, and still retain strict type checks. Big fan of it.
- williamdclt 8y agoif you migrate a TS project with strict mode enabled to Hooks, you will see how much implicit type annotations can be dropped I think you meant "explicit" I agree with you. I've not been too bothered by typing state and default props, but higher-order-components are almost impossible to type properly (a good typedef doubles the LOC count). I don't like that hooks don't abstract away the shared behaviour as well as HOCs (the component is unaware of the HOC while it it aware of the hook), but being explicit isn't a bad thing either and it's definitely worth it if it makes typing a non-problem
- m0meni 8y agoThis is just plain wrong. Did you even read the article?
- thatswrong0 8y agoI’ve been using React for almost 4 years straight - I couldn’t disagree more. Hooks are incredibly useful in removing things that pollute the component tree like higher order components or components with render props which are hard to visually parse. If you have a common state pattern that multiple components use, there’s no good way to share that pattern without one of the solutions I just mentioned.. and hooks are by far the cleanest way to do that. Avoiding prop drilling is so easy with something like useContext. And hooks are always called.. there is no “maybe” when using them.
- arcosdev 8y agoThey solve the problem of me having to use classes at all.
- WA 8y agoIn a way, they are merely syntactical sugar. I agree with the parent poster. Before, you had functional stateless components. Now you have components that look functional and stateless, but are in fact stateful (and impure).
- girishso 8y agoI agree 100%. I think hooks turn pure components into their impure cousins which will eventually make following state changes a nightmare.
- root_axis 8y agoIMO React state managers are an anti-pattern; they were somwhat useful before the final context api was introduced, but even back then simply passing down props is almost always the better choice, even when you're passing down multiple levels.
- revskill 8y agoWith Typescript, it's a non-issue to pass the props down to the tree.