
With React 16.8, React Hooks are available in a stable release - Vinnl
https://reactjs.org/blog/2019/02/06/react-v16.8.0.html
======
BilalBudhani
Hooks 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.

~~~
danabramov
In case you’re curious, I recently wrote up a deep dive on React from first
principles that includes Hooks.

[https://overreacted.io/react-as-a-ui-runtime/](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.)

~~~
BilalBudhani
what a coincidence I just finished reading this article yesterday (and even
Tweeted about it
[https://twitter.com/BilalBudhani/status/1092784595756556294](https://twitter.com/BilalBudhani/status/1092784595756556294)).

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.

------
devit
Are 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.

~~~
danabramov
While HN wasn’t convinced last time I posted this, here’s a few posts or
sections that explain the static call order thing:

[https://overreacted.io/why-do-hooks-rely-on-call-
order/](https://overreacted.io/why-do-hooks-rely-on-call-order/)

[https://overreacted.io/react-as-a-ui-runtime/#static-use-
ord...](https://overreacted.io/react-as-a-ui-runtime/#static-use-order)

[https://github.com/reactjs/rfcs/pull/68#issuecomment-4393148...](https://github.com/reactjs/rfcs/pull/68#issuecomment-439314884)
(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.)

~~~
palerdot
One thing that looks 'magical' is how does the setWhatever function lets React
know that state has changed and has to re-render? Is there any info/writeup on
this anywhere?

~~~
danabramov
Pretty much the same way as this.setState in a class does.

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...](https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-
cd4f1857236e)

~~~
dvlsg
> React knows which component is rendering at any point in time — so it knows
> which component useState() call corresponds to.

Personally, I think that may be the piece that makes it feel a bit magical.
With `this.setState()`, usage of `this` makes me feel like I know how the
component and the state are linked.

With hooks, however, there's no obvious link to the component in the code. I'm
grabbing `useState` off of the shared react module, `useState` is not passed
into the component, and I don't have to reference the component itself at any
point while using hooks. The new sets of rules you have to follow to make
things line up correctly play a part, as well.

Of course that may be how `this.setState()` does it anyways - you know better
than I do, obviously. Maybe the usage of `this.setState()` made me feel
confident in something I didn't actually understand under the hood. But at
least for me, that's why `useState()` feels a bit magical at first glance
compared to `this.setState()`. Not _too_ magical, and not enough to scare me
away from using hooks, but still a bit.

~~~
danabramov
Yeah I totally get that.

Conceptually Hooks are modeled as "algebraic effects" feature from languages
like Eff and Koka. Those are essentially like resumable exceptions.

With that conceptual model, `useState` is like a `throw` that goes back into
React "up the stack", and then goes back into your code.

Of course that's not how it works for perf and other reasons (there's no
resumable exceptions in JS). But this may help the conceptual model around how
we know which component it is.

------
rhacker
Everyone 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.

------
have_faith
I'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.

~~~
danabramov
A 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-...](https://medium.com/@dan_abramov/making-sense-of-react-hooks-
fdbde8803889)

Hope this helps.

~~~
judofyr
But 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, …);
           }
        }

~~~
danabramov
How would you pass values between them?

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...](https://overreacted.io/why-do-hooks-rely-on-call-
order/#flaw-7-cant-pass-values-between-hooks)

~~~
judofyr
[https://codesandbox.io/s/5vvm68k6qp](https://codesandbox.io/s/5vvm68k6qp).
The custom effects would take functions instead of values and then `useEffect`
will be executed by the component. There's certainly some issues in this
implementation with regard to how to handle nested state changes, but I think
that can be worked out.

------
patientplatypus
I 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".

~~~
z3t4
Not specific to React, but with CommonJS modules you can use module scope
instead of global scope to get private methods and variables, which the
function can access via the closure.

    
    
        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.

~~~
crooked-v
That gets you a single instance, but the whole point of React components is
that you can use them lots of time and each will do its own instance of the
thing.

------
Waterluvian
Based 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
Well, 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.

~~~
hesarenu
I 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.

------
sephoric
Now 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
This 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)

------
fiatjaf
Hooks 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.

------
thomasfl
Never 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
A variation on Elm? Why not just Elm?

~~~
coldtea
Well, 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
I 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__
True. I used ExtJS and Ember for years and React just operates on another
level.

~~~
G4BB3R
I 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__
I 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
Something 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
There is a blogpost from dan abramov about using setInterval with hooks:
[https://overreacted.io/making-setinterval-declarative-
with-r...](https://overreacted.io/making-setinterval-declarative-with-react-
hooks/)

------
ricardobeat
Looking 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
This 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?

~~~
danabramov
We’re not refactoring anything at FB and don’t recommend you to either!

We mostly use Hooks in new code.

~~~
aurbano
Sounds good! Absolutely didn’t expect getting a reply from you on this :)

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...!

------
seanwilson
Do hooks work well with TypeScript? e.g. types will catch errors for you and
you don't need to use "any"

~~~
gcommer
Sure, 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/ab08...](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/ab0806bfb5b2ad74dccacd4780be688e96d2ea5a/types/react/index.d.ts#L809)

------
linkmotif
One 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
Use 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
Fun 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
I'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
I 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.

------
azangru
Slightly 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.

~~~
averge
Not 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
> 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
> 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.

------
pacomerh
As 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-
relea...](https://github.com/react-native-community/react-native-
releases/issues/79)

------
throwaway12iii
The crowd goes mild.

~~~
pluma
Nah, 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
Yes, 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
Yes, 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.

~~~
pluma
This 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.

~~~
genezeta
> 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.

In the _exact_ same way that some of the people who are not enthusiastic
aren't people who haven't looked at Hooks and don't understand them. Maybe
they aren't enthusiastic even though they _do_ understand them.

That is _exactly_ the point. Not your experience since the 1990s or my
sarcasm, but not assuming that if someone does not agree with your view must
be _because they don 't understand_.

~~~
pluma
Here's the thing though: people who use React and comment on React news on HN
are a tiny fraction of the overall React community and due to the nature of HN
a lot of people comment on topics they don't have significant interest in.

Negativity is the cultural norm on HN so much that many people look at HN
("the orange website") the way HN looks at Reddit.

I'm not talking about constructive criticism, heck even non-constructive
criticism would be a welcome addition if at least it attacked something more
foundational than e.g. "relying on call order is a footgun" (which btw is true
but ignores the many footguns involved in the APIs hooks are replacing).

You haven't given a single argument why "hooks are bad if you understand
them". That makes you indistinguishable from the usual drive-by negativity. If
you want to appear like you have something to say, maybe you should actually
say that instead of just insisting your opinion is based on something
substantial.

For the record here are the top level responses to the original comment I
responded to:

* omeid2 says hooks are change for the sake of change and they only help saving a few keystrokes

* geezerjay says hooks bring nothing new (then pivots to "no new features" when pushed on it)

And then there's my comment where I say HN is jaded.

The first response by omeid2 is demonstrably false: hooks allow collocating
all code related to aspects of your components that previously resided in
lifecycle methods. They also get rid of the leaky abstraction of `this.state`
and `this.setState`, make it easier (read: less error-prone) to respond to
prop changes and eliminate the indirection required to consume contexts.

The second response by geezerjay is true in a trivial way and false when taken
at face value but further downthread he doesn't elaborate and instead just
insists he's not being understood.

Meanwhile your entire contribution so far can be summarised as "no you" at
worst or "some people don't like hooks even though they understand them"
without going into any tangible specifics at best.

------
wetpaws
Hooks seems like a right solution for a wrong problem.

~~~
k__
How come?

------
ThomPete
I 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.

~~~
ernsheong
My 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.

