16 ms·
With React 16.8, React Hooks are available in a stable release
- throwaway12iii 8y agoThe crowd goes mild.
- omeid2 8y agoThe crowd is too fatigued to get excited anymore, there is a handful of outspoken people who will cheer any change for the sake of change or saving up a couple of key strokes at the cost of long term API size and maintenance burden. but it is getting tiresome.
- geezerjay 8y agoI don't know what is there to cheer about the introduction of a feature that offers nothing new.
- joesb 8y agoHooks offers nothing new over HoC and FaC the same way React offered nothing new over jQuery and EmberJS.
- pluma 8y agoYou're being sarcastic but there are enough people around who wouldn't see that at face value.
- omeid2 8y agoThat is being unfair to React. React changed the way developers reason about UI/DOM from imperative to declarative, the holy grail here is that a declarative API allows you to move up your state and have a "single source of truth" and so makes it easy to reason about your application's state at the cost of having more plumbing, for example consider incriminating the value of an input with jQuery (imperative) vs React (generally with Redux). What Hooks does is move the component's state management from components root a level deeper into hook functions and advocates for reusable state management functions that manages various fragments of your component's state, this I believe is a step backwards in terms of simplifying how you reason about state management in terms of complexity --not lines of code. I am just not sure if this abstraction is worth it in practice and a good step for React.
- geezerjay 8y ago> Hooks offers nothing new over HoC and FaC You've missed the point entirely. Hooks offer nothing new because their functionality was already implemented in React class components. They literally add no functionality to React. The docs actually state quite clearly that developers are discouraged from replacing class components with function components.
- Vinnl 8y ago"No new functionality" and "nothing new" are two different things. Improved developer experience, decreasing the surface area of bugs, etc - all examples of definite improvements that are not technically new functionality.
- joesb 8y agoAnd what do you think React can do that jQuery cannot? Heck, what do you think React can do that standard HTML5/JS API cannot do? React doesn't offer new functionality to do UI. It offer new ways to think about the problem. Hooks doesn't offer any new functionality over `this.state` and component life cycle, it offser new way to think about the problem.
- geezerjay 8y ago> And what do you think React can do that jQuery cannot? Again, you've missed the point.
- alangpierce 8y ago> The docs actually state quite clearly that developers are discouraged from replacing class components with function components. Could you link to where it says this? My understanding is that hooks are intended to be the new best practice, and ideally all code would use hooks (which the React team believes are overall better than class components), but the React team doesn't want to force migration pain on everyone. So as I understand it, it's not that a class -> hook refactor is "discouraged", it's more "don't let this be too much of a distraction, and don't feel obligated to rewrite old code".
- mambodog 8y ago
- pluma 8y agoNah, HN is jaded as usual but every React dev I've talked to outside HN has been looking forward to this day with excitement ever since hooks landed in alpha. I've yet to see HN get truly excited about anything JS-related, particularly React. Personally I'm excited but I wouldn't bother elaborating my excitement here because I know I'll just attract the usual crowd making unfound assumptions about my experience or complaining about hooks not following best practices (like, I don't know, JSX?).
- barryhoodlum 8y agoYes, it gets a bit tedious seeing 90% of comments on HN being from people who clearly haven't tried the thing, or even given it any thought or consideration beyond an initial "this is not familiar to me so therefore bad!" kneejerk reaction. It's not a great look for a developer and I don't know why they seem so proud of their close-minded attitude.
- genezeta 8y agoYes, it gets a bit tedious seeing 90% of comments from React fanboys being from people who clearly just repeat each others arguments, or even give no argument at all beyond "I'm assuming you are stupid because people who are not clearly all love this feature". It's not a great look for a developer and I don't know why they seem so proud of their close-minded attitude.
- barryhoodlum 8y agoI said nothing about loving, or even liking, hooks or React itself. That's not the point. It's weighing in with a completely useless opinion based on a second's thought, over and over again. There are trade offs and it's interesting to discuss those and to criticise them. But a kneejerk reaction can't go that far.
- pluma 8y agoThis is basically the NPC meme but for technologies instead of politics. I've been building websites since the 1990s and web applications since the mid-2000s. I've used a wide range of web technologies and despite being "self-taught" went out of my way to broaden my horizon beyond the imminently useful. My initial reaction to JSX was dismissive ridicule: "XML in JS? Yeah, because that worked out so well when we did that in ActionScript. And building your own component tree as a template language was already a bad idea when I rolled my own implementation in PHP fifteen years ago". My initial reaction to hooks was confusion: "The sequence is important? Why wouldn't you just name things instead? Why does everything start with "use"? What the heck is even going on?" Both times I looked into it and realised I was wrong and my intuition was just rejection of the unfamiliar and a profound misunderstanding of how the technology I was dismissing actually works. I'm not a "React fanboy". I can't say what framework I'll be using five or ten years from now. It doesn't look like there's anything around that I would choose to replace it (though I have to admit Vue is a contender if only because it seems more beginner-friendly) but I've gone through enough technologies all over the stack not to make the foolish assumption that the things I use today will be the things I use in the future. I was confused by hooks, so I paid close attention to the demos and explanations. I learned how they work and why they have the limitations they explicitly tell you to be aware of. That's when I got truly excited. Not because I was dazzled but because I saw the potential and understood how they compared to what I am already using. Stoic sarcasm went out of style in the 90s. Maybe you should give empathy a try. Maybe, just maybe, some of the people who are truly enthusiastic about hooks aren't simply naive, maybe some are enthusiastic because they do understand how hooks work and what implications they have.
- patientplatypus 8y agoI don't get it. I thought the main appeal of functions were that they were stateless so you had immutability. We already have classes if we want state, so why is this an improvement? Functions have slightly less overhead maybe? But then why didn't the React team just work on making classes have less overhead? It seems sort of "extra".
- Bahamut 8y agoI can't speak for everyone, but the reusability with custom hooks looks really nice and better readability than using say HOCs.
- acemarke 8y agoI'd encourage you to read through the Hooks docs [0], which explain the motivations, and Dan Abramov's posts on some of the internals [1] and what problems they're meant to solve [2]. [0] https://reactjs.org/docs/hooks-intro.html https://reactjs.org/docs/hooks-intro.html [1] https://overreacted.io/why-do-hooks-rely-on-call-order/ https://overreacted.io/why-do-hooks-rely-on-call-order/ [2] https://dev.to/dan_abramov/making-sense-of-react-hooks-2eib https://dev.to/dan_abramov/making-sense-of-react-hooks-2eib
- Normal_gaussian 8y agoI've been working with hooks for quite a while now; its main benefit is composability - before hooks up you rely on Higher order components (HOCs, HOFs but in component rendering) to provide composability of component behaviour - this is messy, very messy, and not performant. By using hooks the logic tidies up massively (so working on it becomes a lot quicker) and several hard to diagnose performance bottlenecks disappear. The 'not classes' stuff is a side benefit.
- omeid2 8y agoCan you please give some example of behaviour that you share across components that couldn't be factored out into a function?
- 8y ago
- thomasfl 8y agoNever a boring day being a frontend developer. Looking forward to add hooks to my React project. The next frontier would probably be functional strongly typed languages, like Reason or some variation on Elm?
- yakshaving_jgt 8y agoA variation on Elm? Why not just Elm?
- coldtea 8y agoWell, he said "the next frontier". Probably implies that Elm didn't catch on, and means "what will the next major framework/paradigm/fad will be post-React".
- preommr 8y agoI honestly don't think that there will be another framework that'll overtake react anytime soon. It's not about there being a better framework, just that we finally have something that's "good enough".
- k__ 8y agoTrue. I used ExtJS and Ember for years and React just operates on another level.
- G4BB3R 8y agoI would say the same for Elm architecture and type system that guarantees no runtime exceptions. There is nothing similar in frontend languages and frameworks.
- k__ 8y agoI think Elm is pretty cool too. But last time I looked, the JavaScript integration did feel quite a bit more cumbersome than with Reason.
- omeid2 8y agoSomething that I really like about React is that it is easy to reason about the state of each component, with functions there was no state, with classes, you can see everything that touches the state there in your class. I am not sure how having various functions (hooks) that trigger state changes and so re-rendering is going to pan-out in practice. Here comes setInterval and counter packages, no I don't believe I can simply avoid using them, everyone depended on leftpad, indirectly.
- gurschitz 8y agoThere is a blogpost from dan abramov about using setInterval with hooks: https://overreacted.io/making-setinterval-declarative-with-react-hooks/ https://overreacted.io/making-setinterval-declarative-with-r...
- deleted 8y ago[deleted]
- mambodog 8y agoHow is this different to using a React component installed from npm? You can look inside them if you want to, but don't have to. That is the goal of abstraction. If you want to have no abstraction and show all state in your component, just don't extract any into Custom Hooks. Then it's really not very different to a class component.
- devit 8y agoAre hooks being accepted as a good design by the community? It seems to me that the lack of a parameter explicitly indicating the component and the reliance on hook ordering to match them across calls of the component function make them a bad design, but I might very well wrong and would be happy to be convinced otherwise.
- Lazare 8y agoMy impression is the community is mostly accepting, but some are taking a wait and see attitude until they can see it in production. I don't think there's a lot of concern about hook ordering; it's hard to see that being a serious issue in practice. And it has some significant advantages over existing alternatives.
- emerongi 8y agoMaybe it won't be an issue. However, it does go against regular advice of being explicit over magical. Depending on call order is something that immediately pops out as fishy. As always, programming is about trade-offs and the React team is claiming this trade-off is worth it.
- ricardobeat 8y agoApparently React's internals have been doing similar order-based magic for a while already.
- Vinnl 8y agoThat's also the reason why you have to make sure you're passing an update function to `setState` sometimes.
- jontro 8y agoThat's not why you have to do it, it's because the state can be updated asynchronously. It's only applicable when you try to update the state based on previous state or props values.
- wetpaws 8y agoHooks seems like a right solution for a wrong problem.
- k__ 8y agoHow come?
- ricardobeat 8y agoLooking forward to updating my current project later today. The mess of HOCs, local state, context and props flying around have kept me busy looking for alternative frameworks in the past few years; without those it might actually start being consistently enjoyable.
- aurbano 8y agoThis is exciting, and at the same time I wish this came out before writing thousands of lines of code on my React app... I can see the possibilities this brings, and they're much better than the mess of props, local state, redux, and HoCs that we have. But the refactoring needed is just insane. Has anyone gone through something like this and has any tips?
- Vinnl 8y agoThe primary tip is: don't refactor. It's unlikely to solve any problems if you already have working code in which you've already dealt with all the hassles of HoCs and such. You can just start using it in new code to avoid having to deal with it for that.
- aurbano 8y agoI follow this sometimes but having a wide range of patterns in the same project feels so dirty in a way... Although it makes sense, refactor only when you need to.
- Vinnl 8y agoI understand. I feel like the consideration to make is: will the benefits of hooks outweigh the benefits of mixing different patterns? If your estimate is that it won't, I'd stick to the current patterns for a while, rather than rewriting them now - because I'm quite sure the benefits of hooks aren't going to be worth the rewrite.
- WorldMaker 8y agoI feel like most production React I've seen already has a mixture of components written as classes versus ones written as functions versus functions and classes written to be HOCs. Adding Hooks in most codebases won't make most of them feel anymore "mixed" than they already were.
- cupofjoakim 8y ago
- BilalBudhani 8y agoHooks seem to be a drastic change in how we're going to write React components in the future. I'm quite satisfied with the current way of writing components which is to me is very explicit (with no magic). With Hooks React is taking a different direction from their original motto of explicit design patterns. From the looks of it, Hooks seems like a counter-intuitive design pattern but traditionally that's how most of the JS concepts were before they went mainstream. I'm going to wait and see for some production success stories become giving it serious thought.
- beaconstudios 8y agoHooks fix some of the composition headaches you get from render props, which is the current standard for composition (the heritage being HOCs -> render props -> hooks). They're basically mixins with weird syntax.
- WorldMaker 8y agoThe syntax isn't even that weird? It's just function calls. The only "weird" bit is using array destructuring for multi-return and that's been in ES/JS for some time now, and definitely shouldn't look that weird to anyone that has worked in Python, as one example (and C# now supports destructuring even).
- beaconstudios 8y agoThe weirdness is because the state or context seemingly comes from thin air - there's no explicit location for the data.
- WorldMaker 8y agoThat's not really a syntax problem, though. Also, hidden state/context is also not that weird? Do you need to know the exact location of the memory/stream that `console.log()` writes to in order to log the console? The physical details of how `navigator.compass.getHeading()` gets its information to use a compass heading? Both of those trampoline off into native code and the details of what the actual "explicit" locations for them is both irrelevant and highly variable depending on browser and system. Unless you are looking at the namespace "objects" such as `console` or `navigator.compass` as "explicit locations", but you can add namespaces to your imports if that helps you feel like things are more "grounded". Import it and use it as `React.useState()` instead, for instance.
- have_faith 8y agoI've read a lot about hooks, the reasoning all makes sense but I'm still not fully getting it at an intuitive level. Like I get that it means you can write functional versions of class based components, an example of a complex class component that has been converted to a function with hooks would be good. The counter example really leaves a lot to the imagination. The examples in https://usehooks.com/ https://usehooks.com/ aren't convincing me for some reason, but maybe that's just my lack of familiarity with the syntax so it feels more magic. Lifecycle methods like componentDidUpdate are super easy to reason about at first.
- k__ 8y agoHooks are an alternative to HOCs and RPs. Their bad part is, they add another concept besides components. Their good part is, they allow to convert non-display components to hooks, which removes the guessing of where the logic is stored.
- danabramov 8y agoA major point of Hooks is that they’re composable — unlike lifecycle methods. You can separate different reusable pieces of logic into Hooks, and then combine them or pass values between them. You can even call the same Hook more than once. I’ve wrote about new possibilities they unlock here: https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889 https://medium.com/@dan_abramov/making-sense-of-react-hooks-... Hope this helps.
- judofyr 8y agoBut why does Hooks need to be implemented on top of functions and not classes? The way I see it is that Hooks today implements two distinct things: (1) a composable way to handle lifecycle and (2) a custom way to store state. Why can't we have the composable hooks available on React.Component like this? class Foo extends React.Component { constructor(props) { super(props) this.useEffect(…); this.useState(…); // or maybe even a top-level API: useState(this, …); } }
- 8y ago
- ThomPete 8y agoI am stealing this thread as it seems to have a lot of really knowledgable people in here. I understand basic javascript but I am not an expert and I had a discussion with a developer I want to hire for a new app I am doing, who said that there is no open source components (like quill) which easily allow you to have textformating (bulleted lists, bold, text size etc) and that it would have to be done from scratch) which sounded weird to me since I found a quill component. But I am not a developer so I need to educate myself a little better. What's a good tutorial to get my head around how React works.
- thaunatos 8y agoThe official tutorial would be a good starting point: https://reactjs.org/tutorial/tutorial.html https://reactjs.org/tutorial/tutorial.html
- ernsheong 8y agoMy suggestion to you is to look into web components (e.g. https://github.com/Polymer/lit-element https://github.com/Polymer/lit-element) for theoretically re-usable components. React is optional for web development.
- Waterluvian 8y agoBased on the consistent supply of comments sharing hesitation/confusion whenever hooks are talked about, I'm curious. Is this a normal reaction to a new thing that ends up being a very good idea? Are there past examples of this? I can't quite tell if it's a sign that something's off or if this is just normal.
- fiatjaf 8y agoWell, when React first came out no one was convinced by it. It took more than 2 years, I guess, before everybody suddenly got convinced and started claiming it was the best thing and so on.
- Waterluvian 8y agoTrue. As I read through the blogs about it a third time I'm slowly starting to see what the deal is.
- pjmlp 8y agoNot everybody, I still don't consider it the best thing. I rather use Angular, or eventually VueJS for SPAs, ideally server side with VanilaJS, as not every web site should be a SPA just because.
- hesarenu 8y agoI was not convinced either, Code and UI together!. If you ask me now there is nothing better then reactjs out there. I would not hesitate to change if there was something better.
- fiatjaf 8y agoHooks is awesome! I love hooks! They make everything so simpler. There are less names, less bloat, less stuff to remember. Contrary to what others have been saying, I think hooks is much more explicit than the current class-based components.
- azangru 8y agoSlightly off-topic, but has any of those who dislike hooks for the added magic seen Svelte.js version 3? It is ridden with magic. Top-level variables in the <script> block are "observable" in the Vue sense of the word and accessible in the <template> block; so whenever they change, the relevant parts of the template get updated. The creator of Svelte says that it's very intuitive, and that developer experience is great. I wonder what your take on that will be.
- Tade0 8y agoTo be fair Svelte does have the word "magical" in its motto. I personally don't see it as anymore magical than MobX - it's just taking it a step further by taking advantage of the fact that bindings are created at compile time. This is consistent with how things are generally done in this framework.
- averge 8y agoNot a fan of that non-JS svelte magic or the direction these frameworks are going. Fewer lines of code, true, but at the expense of understandability. I just want to get my work done, not learn yet another flavor of the day with non-intuitive implicit behaviors.
- azangru 8y ago> I just want to get my work done I am generally with you, but the purpose of these frameworks _is_, first and foremost, to get work done (Svelte's creator Rich Harris says that it makes it possible to write UI components very fast). I love it when the code is explicit and when the framework does not introduce any weird shenanigans (Backbone, where are you? I am missing you), but this explicitness comes at a cost of having to write boilerplate.
- averge 8y ago> it makes it possible to write UI components very fast ...until you happen to code something that doesn't follow the magical convention and everything breaks for unknown reasons. Then it becomes difficult - or impossible - to debug.
- linkmotif 8y agoOne thing I can’t figure out in hooks vs recompose is how to use them and avoid props drilling or even just basic wiring. One of the most glorious things about recompose is that the props are drilled/wired for you automatically. This turns out to be huge for me. I had so much tedious props drilling code that just went away with recompose. Anyone have any insight?
- jakelazaroff 8y agoUse the Context API introduced in 16.3: https://reactjs.org/docs/context.html https://reactjs.org/docs/context.html This is the same API that or anything that "teleports" state around your tree uses internally.
- linkmotif 8y agoFun approach! But I don’t think that’s it? Just not the same kind of zero-effort awesomeness right? Also uses the context API for something it’s not intended for.
- jakelazaroff 8y agoI'm not sure what you mean — the context API is specifically for moving data around the component tree without prop drilling. What are you talking about with regard to recompose?
- linkmotif 8y agoI guess I just mean wiring. Recompose eliminates the need to do any wiring at all. You compose up your component, and then you have access to all those props without having wired them! The last thing I want to do is get the context API involved.
- deleted 8y ago[deleted]
- sephoric 8y agoNow we can finally have completely clean data loaders: Create a data loader hook that loads your data in a one-shot effect (you pass it the identities array), and which returns either a valid view (an error or loading view) and no data, or no view and valid data of type T. Then you can just do: const loader = useDataLoader(async () => { const a = await getDataA(); const b = await getDataB(a); return b.data; }); return loader.view || <MyView data={loader.data} /> I've been using this for a few months and it's amazingly clean compared to render-props. I hope this gets pulled into the React standard library.
- basil-rash 8y agoThis also ties in very cleanly with graphQL: import gql from 'graphql-tag'; import { useQuery } from 'react-apollo-hooks'; const GET_DOGS = gql` { dogs { id breed } }`; const Dogs = () => { const { data, error } = useQuery(GET_DOGS); if (error) return `Error! ${error.message}`; return ( <ul> {data.dogs.map(dog => ( <li key={dog.id}>{dog.breed}</li> ))} </ul> ); }; https://github.com/trojanowski/react-apollo-hooks https://github.com/trojanowski/react-apollo-hooks
- rhacker 8y agoEveryone is calling this "magic" yet under the hood it's the same "magic" behind a react component class setState function. It's literally the same thing, but lets you pass these functions to descendents. It essentially decouples that "feature" from being tied to the class component. That's just excellent.
- seanwilson 8y agoDo hooks work well with TypeScript? e.g. types will catch errors for you and you don't need to use "any"
- gcommer 8y agoSure, the "magic" bit of hooks that people are talking about doesn't really affect their type signature See eg, setState: `function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];` from: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/ab0806bfb5b2ad74dccacd4780be688e96d2ea5a/types/react/index.d.ts#L809 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/ab08...
- pacomerh 8y agoAs for react native, I'm glad the docs at least mention they're planning it for 0.59. "React Native will support Hooks in the 0.59 release." https://github.com/react-native-community/react-native-releases/issues/79 https://github.com/react-native-community/react-native-relea...