422 points · by Vinnl · 7y ago · 175 comments
I'm going to wait and see for some production success stories become giving it serious thought.
https://overreacted.io/react-as-a-ui-runtime/
Personally I don’t see them as being either “magic” or “implicit”. You might find my post helpful for conceptualizing how they fit into the picture.
(Warning: it is a longread. But it also explains 90% of React on a single page.)
TBH, After reading the article I'm definitely putting effort to understand the thought process behind this change. Thank for writing up such a detailed & informative explanation on concepts in React.
Now hooks are certainly a technically interesting pattern. I can see why it can be desirable by some. But I can't shake the feeling it has too of a big potential for misuse and could add a lot of complexity to a react, a tool that already has a big cognitive load with an ecosystem letting easily creep technical debt.
Besides, an important part of the JS community, up to now, has let me inconvinced about its ability to do the right thing, not to mention learning from other's past mistakes or even admitting when something is a problem at all.
Your post boils down to "Seems like it might be nice, but there might be bad sides, too" which seems fair, but the rest of your post is dressed up in a weird gloating dismissiveness and an exaggerated narrative about you, the epic heroic, fighting back the baying React Fans like in Doom's cover art.
I wouldn't celebrate your skepticism just yet, especially not just because you found someone else on HN to commiserate with.
There have been what I think are some convincing arguments for it in the comments and linked urls like https://overreacted.io/react-as-a-ui-runtime/.
- hooks are technically interesting, but make it easy for humans to screw up. It's a precise critic.
- the JS community has bad habits that can catalyse this, and above all, may lead them to avoid seing what's wrong
- they get angry when we say it, and dismiss it as nonsense.
Case in point.
I don't understand how hooks add complexity or cognitive load. Simple cases stay simple (even more so, and it's harder to mess up with useEffect than with lifecycle methods, for example), and complex cases are less so.
From the point of view of someone with years of experience writing large applications with React, hooks are a very pragmatic move that solves real problems precisely by simplifying what was already possible. The more complex the scenario, the more obvious the gain is. I venture to say the same thing about the upcoming suspense and related features.
I don't think React itself has a big cognitive load anyway. You might be attributing to it the difficulty some aspects of functional programming might present to some, or of some libraries you might have been using with React. I found this to be the case often. Forgive me if I'm guessing incorrectly.
But more than that, react based code has a lot of indirections, requires a lot of pieces of the puzzle to figure out what's going on, and projects have so many different styles and layout you never feel at home when you switch.
The best exemple is jsx. Not only you need a transpiler, not only do you mix in the same place representation and behavior, but the code looks like either spagetthi inlines, or, if you are lucky, a list of many references you suddenly gotta check up somewhere else.
The thing is, with classes, you have a little guidance on where goes what, and people still manage to screw that up. With hooks it's free for all, with caveats, so reading somebody else's code is going to get extra fun.
[1]: https://overreacted.io/why-do-hooks-rely-on-call-order/
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).
No offense, but it would sometimes be good to remember that quote about sufficiently advanced technology being indistinguishable from magic when taking such an authoritative tone.
There are probably some other equally talented developers who do ‘get it’ who might be a little unsure of themselves and continue to hold back and feel like an imposter.
Anyway, that’s not really a call to change or anything. You do you.
But I did want to remind everyone else, especially those unsure of themselves, that those are, like, their opinion... you also do you.
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.
https://overreacted.io/why-do-hooks-rely-on-call-order/
https://overreacted.io/react-as-a-ui-runtime/#static-use-ord...
https://github.com/reactjs/rfcs/pull/68#issuecomment-4393148... (Persistent Call Index section)
Hope this helps, happy to answer questions. We’ve been using Hooks for several months at FB and haven’t seen confusion caused by the call order reliance.
(Note Hooks don’t rely on specific call order but just on it being static between renders. Which is pretty easy to understand and reasonably enforce in practice.)
React knows which component is rendering at any point in time — so it knows which component useState() call corresponds to.
I think this explanation is quite accessible:
https://medium.com/@ryardley/react-hooks-not-magic-just-arra...
It's basically the magic vs explicit discussion all over again. Like usually in this discussion, the magic approach is really appealing until it doesn't work, and then the pro-explicit people will go all "told you so" on you.
I personally really prefer explicit, having cut my fingers on magic one time too often. Instead, I'll gladly create classes if the thing I'm making has its own state (of any kind).
In fact I pretty much disagree with the current trend of wanting to shoehorn everything into this idea of declarative and/or functional programming. Especially in a language like JS, functional programming and some cherry-picked ideas from OO mesh really well together. For example, if you allow me to drift a little, did you know that you can add methods to the prototype of an Immutable.Record? You can even use class syntax! More to the point, if there's one place where OO ideas shine, it's UI components. A lot of OO ideas were particularly designed and developed for UIs.
Just like "let" and "const" let me communicate to the reader whether a variable is going to change, I like how in React-land "class" and "function" let me communicate to the reader whether a component has mutable state. Hooks feels like a hack to be able to change the value of a "const" without turning it into a "let". Get over yourself, make it a "let" already.
So for me, Hooks is an attempt to throw the baby out with the bath water. I don't experience the problem it's trying to solve. I like classes when they're appropriate.
I get the argument that custom hooks allow for easier reuse than higher order components, but I think the difference is marginal; you have to wrap your mind around the exact same complexity. Plus I think higher order components themselves are overused, but that's another story.
But! The React people strike me as a rather reasonable bunch. I strongly doubt they're going to move React into a direction where you're forced to make your state (slightly more) implicit. There's too varied a community around React now. I think React with classes and React with hooks can perfectly coexist. Also if my favorite open source React tool adopts hooks and forces me to do the same here and there, then sure I might be grumpy for a few minutes but in the end, well, I'll survive.
Well... Have any "pro-explicit people" gone all "told you so" about all the magic that's going on with setState?
I don't think so. I don't think it's a binary magic vs explicit choice. I usually lean towards explicit, but as setState demonstrates, it's possible to find some kind of balance where the benefits of the magic outweigh the downsides, or at least are not that bad of a choice.
> lack of a parameter explicitly indicating the component
That's sort of the whole point. That you can write general purpose side effect functions that don't need to care about which component they're being used in. It's super easy to have a toolkit small unit testable functions that do the pretty much all the work in the application. Far easier to work with than inheritance, mixins or traits. Easier than composition, even, because this is just calling functions. If you're familiar with using Underscore or lodash, this model will feel very intuitive.
> reliance on hook ordering
This is a red herring, because we're only talking about execution ordering when the code runs. It doesn't actually matter what order I write any code in, only that when the code runs the order doesn't change between two render frames. This is as simple as don't have conditionals outside the hooks, have them inside. If you think of hooks as accessing the state register by the index of their first access, it works well as a rule of thumb.
The real problem is the impedance mismatch that the line above causes - you need to remember that hooks access the state register by order of their first appearance, not by identity. So if hook no. 3 doesn't execute on the second render for some reason, hook no. 4 will see hook no. 3's data. This goes very contrary to JS or any other programming language / paradigm I know.
It also has repercussions (https://overreacted.io/making-setinterval-declarative-with-r...) that are unintuitive, because the identity of the functions you pass into the hooks is lost as well, so you need to put them into the call-positional state register via a ref.
To be honest, I haven't hit that edge case yet, and it's easily handled once you understand the system for what it is. It is very un-intuitive to program this way, but it's not a problem most of the time.
Just remember that the identity of the state of any hook is represented only by its sequence number of execution during the first render, and you can figure out the remaining gotchas from that.
The cannot be called in conditionals and/or loops need is certainly more rare, but it's also not necessarily an exotic thing: so much of debugging and performance work in the average imperative language is often finding things called conditionally or in loops that shouldn't be and moving them up/out. Some things like setInterval or certain types of awaiting large expensive computations you almost wish you had lint errors in place to forbid them in loops (or even sometimes to forbid them from conditionals in cases where they don't happen cause subtle bugs).
I don't think this is contrary to JS at all. It's different and may take some time getting used to, but "call order matters" isn't unusual for JS (especially in the world of DOM manipulation).
The declaration parts are always static and in the exact same order for the same component.
When you see a state less function
ToggleButton = () => {
const [flag, setFlag] useState(false)
const [count, setCount] useState(1)
const useEffect(()=> {....})
return <button onClick={() => setFlag(!flag)>{flag}</button>
}
View it as a component with two separate sections, behavior declarations and actual rendering: Component ToggleButton
// declarations
hasState: "flag" setterName: "setFlag"
hasState: "count" setterName: "setCount"
onEffect() { .... }
render() {
return <button onClick={() => setFlag(!flag)>{flag}</button>
}
}
Then you will see that reliance on hook ordering being the same is what you always do when you write a declarative code anyway. class ToggleButton extends React.Component {
flag = useState(this, true)
count = useState(this, 0)
other = useEffect(this, () => {
...
})
render() {
return <button onClick={() => this.flag.set(!this.flag.current)>{this.flag.current}</button>
}
}
Then it's very clear that we have two separate sections: initialization and rendering. There's no longer a hidden state stored somewhere else, but you know that if you have the same `this` then you have the same state.I tried to explain this here:
https://overreacted.io/why-do-hooks-rely-on-call-order/#flaw...
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.
As always, programming is about trade-offs and the React team is claiming this trade-off is worth it.
function foo() {
let x = 1;
let y = 2;
x + y;
}
Your code already depends on ordering. x is on the stack first. y is on the stack second.You don't randomly rewrite this two lines of code on every invocation of foo.
`let x = 1` and `let [x] = useState(1)` is the exact same thing.
tl;dr: The primary design goal of hooks is to support the creation of custom hooks, which can eliminate the need for higher-order components in many cases. An ideal alternative implementation would support custom hooks, without relying on call ordering, and without requiring a linter to guarantee safety. Unfortunately, there doesn't appear to be an approach that satisfies all of these requirements. Depending on call order is apparently the least-bad approach to hooks.
I just enjoy turning his sentences into blog posts. :-)
I guess even the React team itself doesn't have an answer for this, that is why they are rolling out Hooks relatively cautiously, not forcing it down to the community like what angular does with its 1.x -> 2.0 push, which I consider as a complete disaster that eventually costed it the victory of last framework revolution.
My bet will be on the later. Hooks will become a preference, and there will be a mix of hooks/classes in real world application, since rewriting using Hooks only isn't what most people see will bring immediate benefits. The React community at large from my observation doesn't have a huge issue going forward with the current API, despite being grumpy from time to time.
I think they will be the standard going forward.
The examples in 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.
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-...
Hope this helps.
class Foo extends React.Component {
constructor(props) {
super(props)
this.useEffect(…);
this.useState(…);
// or maybe even a top-level API:
useState(this, …);
}
}Note Hooks execute on every render. That’s their whole point.
I explain this here: https://overreacted.io/why-do-hooks-rely-on-call-order/#flaw...
Grouping these parts this way means they can be trivially extracted as a Custom Hook[1] (analogous to a 'mixin' or 'trait' in OOP).
By extracting this concern into a Custom Hook it can easily be reused by different components, as well as composed by other Custom Hooks. This was previously possible using Higher Order Components, Render Props and the (really old) React Mixins concept, but Hooks addresses problems with each of these previous approaches.
If you want to know more about how Hooks improves over these previous approaches, see my previous comment: https://news.ycombinator.com/item?id=19074469
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.
But the benefit is tighter encapsulation of functionalities. No longer do we have to spread a feature's logic across multiple lifecycle methods that may share that space with logic from other features.
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.
https://medium.com/@dan_abramov/making-sense-of-react-hooks-...
Hope it helps!
A HOC previously served as a minimally invasive way to compose these behaviours (compose the HOC + use its param in render).
If you are writing a moderately complex animation, you can quickly end up needing state, willMount, and willUnmount, plus the render change plus the logic, thats five places in a class. If this animation applies to many components you abstract to a HOC and simplify dev overhead at a performance cost.
Using a hook lets you abstract that all into one function as you suggest.
Most of the HOCs I wrote had to do with just local state + store state + logic, so not as extreme (editable, updatable, draggable, deletable etc.); but when you have many, the penalty adds up.
[0] https://reactjs.org/docs/hooks-intro.html
[1] https://overreacted.io/why-do-hooks-rely-on-call-order/
[2] https://dev.to/dan_abramov/making-sense-of-react-hooks-2eib
var foo = 1;
var bar = x => x++;
module.exports = function baz() { return bar(foo) }
I find this much more simple then classes. I even consider it an anti-pattern to make a class for something this simple.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.
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. 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-hooksContrary to what others have been saying, I think hooks is much more explicit than the current class-based components.
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.
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.
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?
We mostly use Hooks in new code.
I’ll use them in a couple new features and see how nice and tidy I can make things look, then think about how we’ll continue going forward.
Still have a bunch of componentWillReceiveProps that need attention as well...!
See eg, setState: `function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];`
from: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/ab08...
This is the same API that or anything that "teleports" state around your tree uses internally.
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.
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.
...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.
"React Native will support Hooks in the 0.59 release." https://github.com/react-native-community/react-native-relea...
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?).
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.
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.
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.
React is optional for web development.