As non native speaker I had to look for “black box” in the English dictionary:
> (informal) a complex system whose internals are not easily understood.
So what the article author does not understand of React internals? I don’t care about React internals either until the API is well written and easy to understand. Hooks did not go in this direction :)
This is the kind of post that suffers from lack of specific examples. I would love to see an interesting discussion of how hooks are not in line with most developers mental model of React and what problems it's causing (if that is indeed true, or at least true in the eyes of the author). But this post is far too generic to illuminate what the real problems are or convince me that there are any.
In fact, it smells like the author doesn't know what he's talking about; in my experience "That will break for the following incredibly subtle reasons:" is usually about React fundamentals such as being deliberate with state mutations.
Custom hooks are some of the most useful and fun code to write, in my experience.
I was going to say - the main reason why I like Hooks is because it's a lot simpler to reason with compared to classes, and it makes it easier to avoid whole classes (heh) of bugs.
If anything, React is becoming less of a black box, with a 'simpler' API. It's just that in the process to moving to or learning the new API, people are understanding they didn't actually understand React before. They're now being made to confront that.
Formik started as a class-based library and most likely still uses some under the hood. Maybe he's just not a fan of the hook API and prefers the other way?
Fwiw, we have a stable admin client that uses Formik. One month, I went to update dependencies. Since the admin client was stable, I only updated its deps for minor versions. Four weeks or so later I get a bug report for that client. Nothing obvious or non-obvious jumped out at me in the component of concern and its blame. After git bisecting, it turns out the minor version bump to Formik had a breaking change.
I've only touched that package a few times since but it never fails to make me wish the original lead hadn't used Formik. I dunno, forms in react have never given me tears, but contrary to Formik's slogan it has been painful, even aside from this versioning fiasco, so I'm not sure this endorsement is as strong as you think it may be.
I'm not endorsing Formik in any way, but I don't think making an accidental breaking change in a minor version is exactly a cardinal sin.
What I'm saying is silly is to say the author is somehow "uninformed" when it comes to React like he's some sort of newbie, as opposed to the guy who wrote the library that a sizable percentage of React apps use for their form components.
The author is Jared Palmer. He's a well-known engineer who has worked with React for years, and the author of a very popular OSS React library (Formik).
I used Formik long before hooks, then later, after hooks. I remember hesitating a few times because some of the exceedingly neat pattern/syntaxes were impacted negatively by hooks.
I still "happy" with both, but my team is all quite senior and I feel for jnr teams trying to grapple with React AND hooks at the same time.
Can confirm that Formik's hooks API is really not very good. Any change to any form component results in the entire form rerendering when hooks are used to connect to Formik context. Lost months of time in last gig to the choice to use Formik.
Although the article is too generic, or not detailed enough regarding examples of what he states, I have to agree with what he is trying to say.
React hooks are a mess, or at least code based around it tends to be. We have had our share of hooks based applications and they've become unmaintainable when reaching a certain size and I am glad that we are back to class based components wherever we can. In may opinion this comes down to the fact - as he states - that the mental model (what will happen, when I do this) is not simple to grasp, thus not predictable for many people.
> React hooks are a mess, or at least code based around it tends to be.
I've read a lot warnings about the pitfalls, and about hooks not doing what you think they are doing, but honestly, I haven't experience any of that, maybe because my use cases are so close to the documented ones, that I don't need to stretch the concept, and it just works as intended for me.
Could it be, that as with many other programming patterns, some developers are using it as a silver bullet, and trying to solve everything with hooks?
Otherwise I'm failing to understand, it would be useful to see examples as the mentioned above.
Hooks are a bit of a double-edged sword in my opinion.
On the one hand, they are nicely composable. You can make one hook call depend on another and you can easily build a lot of cool functionality thanks to this. On the other hand, you are no longer able to directly follow the flow of the code. Making a change to a series of hook calls can sometimes be scary to me as it can be hard to fully understand the cause-and-effect of that change.
On the one hand, you can hide a lot of complexity behind a simple `useSomething()` call, on the other hand the code inside `useSomething()` can be absolute horror, because all the stateful logic is handled through hooks. Any non-obvious use-case ends up being a mess of hook calls. If you only write the code once and never need to touch it again, `useSomething()` can be an amazing hook though. There are some hooks that I have written that I hope I (or anyone else) don't ever have to touch. I might just be a bad programmer though, or missing some obvious patterns.
TLDR: hooks work well, but they have downsides in terms of maintenance burden
On the other end you can compose class components which have lifecycle methods which you need to jump through up and down the code to figure out the full behavior. Which to me is much more unreadable than hooks and effects. Not to mention that lifecycle methods have their own gotchas.
> On the other hand, you are no longer able to directly follow the flow of the code.
Hooks are, at least as they're presented on the surface level, exceptionally functional, so shouldnt it be easier to directly follow the code? Just follow the function calls?
I am mostly a spectator in this argument, since I'm holding out as long as possible on committing to hooks, but the impression I got from the React Hooks FAQ is that hooks are supposed to be a silver bullet:
> Should I use Hooks, classes, or a mix of both? [0]
> When you’re ready, we’d encourage you to start trying Hooks in new components you write. [snip]
> Do Hooks cover all use cases for classes? [1]
> Our goal is for Hooks to cover all use cases for classes as soon as possible. [snip]
The answer about higher-order components is a little more nuanced but does say hooks should replace most of them:
> Do Hooks replace render props and higher-order components? [2]
> Often, render props and higher-order components render only a single child. We think Hooks are a simpler way to serve this use case. There is still a place for both patterns (for example, a virtual scroller component might have a renderItem prop, or a visual container component might have its own DOM structure). But in most cases, Hooks will be sufficient and can help reduce nesting in your tree.
Learning enough about the React lifecycle to make simple apps was a big task, but it felt like a bounded one for my purposes. Learnings hooks seems... strangely open-ended. There's a small set of built-in hooks that do certain things, and if I need more I'm supposed to build new hooks out of the old ones, and that's supposed to be it. Except that it isn't, because if that's all there was to it, people wouldn't be having difficulty. I just wish the rest of the story was sketched out and bounded for me in some way so I could know what I was getting into.
I remember people having difficulty with callbacks, then with generators, then with promises, Obersavables... you get the point.
There is always something new that tries to make 80% of the cases trivial with a new elegant syntax that hides a lot of complexity, and comes with that 20% of cases where it is harder to grasp.
You realize you've just done exactly what the parent complained about right?
- said it was bad
- not provided any concrete details
> they've become unmaintainable when reaching a certain size
How?
Did you start getting lot of hard to replicate bugs?
Did you find authoring new components was made difficult by your heavy use of custom hooks that were actually not as generic as you thought when you wrote them?
Did you find 3rd-party hooks had bugs?
Did you find that useRef doesn't work like you think it does, and you can't mix and match useRef and useEffect? (ouch)
What kind components are you writing that you find hooks are such a bad fit for?
Be specific.
(I'm not saying hooks are perfect; I've had all of the issues I listed happen to me, but it's still quicker to implement new features on a medium sized web app using hooks than with components in my experience; I work on 3 apps, and only one of them still uses components, and it's the most annoying to make changes too, simply because for simple business components & forms, hooks seem to reduce the amount of boiler plate, and flat out, reduce the lines of code; less code -> faster changes. It's not always that simple (see bugs comment above), but mostly... it is, in my experience: ...HOWEVER, what you've done is just wave your hands vaguely and fail to actually say anything except you don't like hooks)
You don't need to understand all the stuff you use.
How complex it is is not relevant unless it has a tangible impact.
eg. I use spark a lot. I don't really deeply understand how the DAG is translated into a distributed computation and the results are aggregated from the cluster.
It calculates things. It's fast. Sometimes I'm surprised by things that are slower than I expect. Oh well. Don't do lots of column renames. /shrug
It's a tradeoff.
Is the effort to understand the detail worth the benefit of doing so? Does not understanding it cause enough pain that it become prohibitive to develop using it?
Is it for spark? No. I really don't care how it's implemented. I don't even know scala. It works fine.
Is it for assembly? No. I don't care at all how my code is JIT'd to assembly / code. It just works.
It it for react hooks? I honestly haven't personally found it to be... but I don't write custom hooks much.
So, your experience with hooks might be different, and you may find the trade-off is more expensive if your case, because it tangibly causes, eg. bugs when you write your code.
...but you are quite wrong if you think that not understanding how something works is a fundamental obstacle to using it.
That is categorically false.
I would argue that it's far from proven that using complex systems necessarily causes the complexity of your system to balloon out of control... or that there is even a strong casual relationship between "mental model being complex to grasp" and the resulting complexity of the system.
Thats the point: the mental model is irrelevant unless it causes bugs when you use it wrong.
Does it? Does it actually cause bugs?
Not, “in general”; You’re just doing the same thing again here and doing vague hand waving. What actual bugs? What types of bugs?
Be specific
(yes, it does cause bugs, but see how this conversation is pointless when you don’t provide any details? Right, now go read the first post in this thread.)
> ...it's far from proven that using complex systems necessarily causes the complexity of your system to balloon...
I don't know what "proven" would actually mean in this context, but there's a notion called "leaky abstraction". It bites you hard when you use a "do-everything" framework and something goes wrong.
All of sudden, the magic stops and you have to deal with a ream of obtuse stack traces, problems that completely smash your metal model of what's going on, and you end up in deep rabbit holes of stuff you don't want to get into at the worst possible time. That is a fundamental obstacle.
All things given, I'd rather use a tool that does not have leaky abstractions and if I need to investigate the inner workings of an abstraction, I can form a mental model of that abstraction with little effort. To your point, you don't need to understand the inner workings of your tools, but being able to quickly learn about the inner workings of the tools is beneficial to creating abstractions, crafting solutions, fixing issues, performing refactoring, tracking the usage of concepts across the codebase, etc.
How is the mental model hard to grasp? Hooks are just functional components. They render information like everything else. Following the same rule set. State change? The hooks renders. Parent renders? The hook renders. Want to stop it from rendering? Use a memo. Want to run logic only when certain state changes? Use an effect.
My experience has been the exact opposite. Class-based components encourage creating large monolithic classes because it's hard to split class methods into smaller units.
With hooks however, you can create self-contained custom hooks that group all the code of a feature in one separate file. It's much easier to test and to make sense of. It's also easier to make the hook more generic and re-usable when it becomes needed by other components.
I'm definitely not going back to class-based components as I find React hooks a lot easier to manage and maintain.
I’ve had the exact opposite experience. I loathe class components and convert to hooks whenever I can. Class components seem so bloated and enormous with anything but the most simple use cases.
Sometimes when I read these comments I feel like I am using a completely different library.
Which means you can call it inside a for loop if you have guarantees that the order will always be the same. These are the caveats that don't fit in one paragraph. Also, repeating the rule 'it has to be called in the same order' is not explaining how it works.
You could say each call corresponds to a timestamp and they need to be ordered, and the person receiving that information would be none the wiser. It just doesn't lead you to understand what's happening underneath. Some may be fine with stopping at that level of understanding, but the stack-based approach of hooks is quite unnatural for JS and I don't think it is good in the long-term for developers to just 'accept' that as supernatural.
So in order to understand not only the basics of the rule, but also the underlying implementation and exactly in what way it would crash, it may require more than a paragraph. I'll concede that. But this is common in programming. As an example, you'd probably spend some time understanding exactly why it is you can't free a pointer twice in C.
There's nothing stopping someone from reading the explanation in the React docs[0] if they want to understand.
> This is probably the only React hook nuance you really have to understand
Absolutely not. There is the dependencies array, how it only does a strict equals check (no shallow comparison), how you need to memoize other dependencies so they don't change on every render, why it is a problem to leave it empty, why useEffect cannot strictly replace componentDidMount, why you can't put one hook inside the other, how (and which) hooks can trigger a re-render or block updates, how state is captured by the closure and what to do if you need current state, how to persist things across renders using useRef.. and probably more.
Something that I still don't grasp with React:
1. Your render function runs quite often, e.g. on each state change.
2. But it runs a bit differently sometimes: const [a,setA] = useState(1234);
Here "a" will have the value 1234 on the first run (what is a first run? When react instantiates this component? When it mounts?) Then this same line of code will assign a different value to this same variable, because setA was called in the past. Why? How does it know that this exact local variable needs a different value?
1. When React mounts your component, it creates an object to contain its internal state, including the state of all hooks.
2. Before calling your render function, it stores a reference to that object in a private, global variable. (Global in the sense that there's only one per JS VM) (Javascript is single-threaded so this is perfectly safe to do).
3. Each of the built-in hooks has access to that variable, and use it to increment a number representing the current hook index and then store information in an array at the current index.
4. The next time your component is rendered, that information is still there and the hooks can retrieve it.
5. Also some hooks like useEffect set up functions to be called by react later.
const React = /* Implement this */
function HelloComponent(){
const [myNumber, setMyNumber] = React.useState(0);
// Simulate rendering data to a screen
console.log("My number:", myNumber);
// Simulate rendering a clickable button
const click = ()=> setMyNumber((num)=> num + 1);
return click;
}
React.mount(HelloComponent); // prints 0
React.simulateClick(HelloComponent); // prints 1
React.simulateClick(HelloComponent); // prints 2
React.simulateClick(HelloComponent); // prints 3
General idea being that the React item may be stateful, but the HelloComponent must be a stateless pure function. How can it draw on React's statefulness, while only using that useState() call?
I am working through this exercise now, but I'm already finding myself doing some pretty hacky things to make this work (like finding out who called a function using arguments.callee.caller.name). Still, it's pretty interesting.
Checking the function's caller breaks the composability of hooks: it stops hooks from being called by other hooks. (Also, it doesn't work in strict mode, which is enforced when you use ES modules.) React is the only thing that calls component functions, so React can just remember what component is being called before it calls it. I've posted a reply on your gist with an example that addresses this.
Very cool! appreciate the response, very interesting to see an improved solution on this.
I was mainly interested in solving for how React lines up the useState calls with the actual data that it's keeping under the hood. So I definitely cheesed through the parts touching on how React keeps track of the component tree.
I'm enjoying reading through your interpretation of this though. Thanks
Render functions are only called when a component is being rendered. React keeps track of which component is currently being rendered. When you call `useState`, React knows which component is currently being rendered and keeps track behind the scenes which state that component has.
The way it knows which value it should return for `a` ties directly in with why you need to call `useState` calls in the same order -- React basically keeps a list of the state behind the scenes, and returns the (secret behind the scenes) state in order. If you change around the order of `useState` calls, it can't use the ordering of the calls to determine which state needs to be returned.
and I change the value of isLoggedIn. Does the state reset? I'm not asking for a solution, just pointing out that even a 'simple' hook like useState has its small quirks.
It does reset, because toggling that flag will unmount the old instance of the component, and then mount a new instance.
This is the same behavior as has always existed with class components and `this.setState()`. Component-scoped state only exists as long as that specific instance of the component is mounted.
Most of these are also true pre-hooks, it just wasn’t as clear that they were actual concerns and most users ignored them, leading to horribly slow but still functional code. Hooks drive you to more correct usage but the consequences of misuse become more severe.
> There is the dependencies array, how it only does a strict equals check (no shallow comparison), how you need to memoize other dependencies so they don't change on every render
So basic memoisation?
> why you can't put one hook inside the other
Hooks inside other functions may be called at any time, how is React to know which component is calling them?
No. Before you just had to worry about shouldComponentUpdate and data received from the 'outside'. With hooks you need to memoize arguments to every function you call within the component - you didn't have to memoize class methods. The concerns and patterns involved are very different.
Yes! A hook call occurs at most once per render. For react to figure out which hook call corresponds to what state, it analyzes the call order. Because we write component render functions top down, the hook call order stays the same every time every render. Not so if we call a hook inside a loop [1].
Why would you call a hook inside a loop anyway? Hooks return callbacks and variables, which you can use inside a loop without problem.
Just as you don't call this.componentDidUpdate in a loop. I'm reading through the comments and trying to figure out what mental model some have of React that causes them to just don't "get" hooks. I'm starting to think this difference in thinking did not start with hooks.
Hooks aren't always comparable to lifecycle methods. At my company every GraphQL query/mutation has a corresponding hook. There are frequently times when devs are tempted to use them, especially the mutations, in for loops.
Because React keeps track of the hooks you are using by the call order, and a loop might indicate than in different rerenders it might have different lengths. You actually can do it, it's just the linter trying to avoid you shooting yourself in the foot.
In fact the linter explains exactly that in a paragraph:
> React Hook "useState" may be executed more than once. Possibly because it is called in a loop. React Hooks must be called in the exact same order in every component render.
A trend I've been seeing on HN and Reddit alike are articles that are not in depth, but allow the users of the medium in which they are shared to have a reason to talk about something. This post probably got more attention because it was a dedicated link versus somebody asking HN if they think React is becoming a black box.
I'd much prefer the latter, but it seems that links are the way of websites such as these.
The quality of posts at the top of HN has really tanked over the last 2-3 years. Falling from high quality to “programmer clickbait” like the OP here. It’s a little better if you use /classic as a path, which I understand is only calculated by upvotes from users from the first couple years of HN, before the startup boom. Occasionally /news and /classic are virtually identical making me wonder if there are a lack of active OG users and the algo falls back to default during a lack of classic participation.
I can give example. Svelte has actions (here details https://svelte.dev/tutorial/actions). You can take pannable action as a starting point from that page. Now try to write React hook that does the same as pannable Svelte action. You can do it. There are "problems" however:
1) React solution will need a little bit more lines;
2) There are multiple ways to write that and some ways are less efficient than others;
3) React solution is harder to write if you only started with hooks.
I'm going to use React because:
1) I don't need to learn anything new (only hooks) to do what I need;
2) I have richer environment: typescript, testing libraries and all React libraries/solutions I might need. Svelte is getting better and potentially it already covers things I need but that was not the case one year ago.
I don’t get it. You don’t really need to understand how React works, you just need it to work. If you’re building a React app you’re probably just building some simple CRUD like thing. What are you going to abandon React for? Some other black box?
> Remember that React is supposed to take care of the “how” so that we can focus on the “what” of our apps. This mantra though, assumes that we can predict the “how”-part correctly.
Their claim is that it's becoming increasingly difficult to predict how React is supposed to work in different scenarios.
Yeah "black box" is the totally wrong phrase/metaphor here.
"Black box" means you don't know what happens INSIDE the box. A very succesful software abstraction might be a black box, this isn't generally considered a negative in software. A good "black box" is completely predictable from it's interface, even though you have no idea what's actually going on inside of it.
To me, "accessing disk IO" is a "black box", I have only a vague idea what happens inside the black box when I ask to read or write bytes; and I don't need to, because it works reliably and my very simple mental model of how it works serves me. (If I was doing realtime or high performance or something, I might need to go inside the 'black box', making it no longer a 'black box' that you can't see inside, but I am not and have not).
Wikipedia: "In science, computing, and engineering, a black box is a device, system or object which can be viewed in terms of its inputs and outputs (or transfer characteristics), without any knowledge of its internal workings."
But that's not actually what OP is talking about.
The author is not actually complaining that it's a "black box", he's complaining that the inputs and outputs of black box are too hard to understand, that the mental model of what the black box does is too complex, that it's no longer predictable what it does.
This article might get upvotes because people agree with that basic conclusion, it matches their experience. But it's a pretty poorly written article. It has no examples or evidence, and it's central point is poorly expressed using the wrong terminology or metaphor.
> If you’re building a React app you’re probably just building some simple CRUD like thing.
Simple CRUD-like thing? Why would you reach for a front-end framework such as React to build it in the first place? Ideally, React should be used to solve sufficiently complex problems.
This is kind of just explaining supply and demand. I would say a large proportion of React devs just want it to do the things they need and easily, and hooks certainly aide them. Sure if you need to dig a little deeper then you find that hooks can be a warren of complexity - but nothing stops you from approaching the code directly to understand more (and you can still use classes). For me and my team we actually leverage the 'black box' nature of hooks for the good of the team. Senior members can write high level hooks that they understand and juniors can just use them in their components and not need to go too deep too soon.
This is a really disappointing take on so many fronts.
First, definitely lacks a historical perspective. The React team is certainly not new to accusations of banking their platform on certain mental/implementation/stylistic decisions which people REALLY scratched their head at, only to then become the behemoth of a framework that it is. JSX???? CSS and JS in the same file??? Etc.
But more importantly, this completely overlooks the amazing work the core team has done to make sure you DO NOT NEED TO TOUCH ANY OF THIS STUFF AT ALL if you never want to. React powers one of the most complicated and widely available web apps in the world. That the company and team building it are including tools and philosophies which feel awkward for your CRUD app should simply feel... right. But what certainly doesn't feel right is to see the core team build out more and more features, which support more and more advances and highly specialized use-cases, only to then see the community turn on them somehow because it is "too complicated" or a black box.
> I think a good ol’ Pete Hunt-style “Thinking in X mode” blog post would go a long way.
They point out that maybe all that's missing is a simple explanation of the thinking behind the new React features is, much like React and its developers did when they first introduced ground breaking features.
> React powers one of the most complicated and widely available web apps in the world. That the company and team building it are including tools and philosophies which feel awkward for your CRUD app should simply feel... right. But what certainly doesn't feel right is to see the core team build out more and more features, which support more and more advances and highly specialized use-cases, only to then see the community turn on them somehow because it is "too complicated" or a black box.
Not sure if you can blow more smoke up Zuckerberg's ass?
I feel like we need a new word: 'trickle down software' (in the pejorative sense). It recognizes that the corporatocracy has plundered the Commons/public domain [1], and are 'gifting' us frameworks like React while keeping the most useful strategies and mission critical frameworks and strategies for themselves.
Maybe I should just stick to campaigning for 1) Protocol Cooperativism using Arthur Brock and Eric Harris-Braun's Holographic chain distributed application framework, together with 2) Mikorizal.org's Holo-REA economic framework - an Open Value Network (OVN) based on the Resource Event Agent (REA) accounting model (first developed by Bob and Lynn and Tiberius), which works as a transparent alternative to black-boxed corporate Enterprise Resource Software (ERP). OVN's can be used to fund open source hardware projects, and help with the transition to Commons-based peer production.
But I just think someone needs to point out the hypocritical and 'privacy-washing' behavior of corporations who 'open source' non-critical pieces of code and then leech on free software developers and destroy and corrupt these people's hacker+maker philosophy with wads of cash and a life of consumerist 'luxury'.
All of these actions are in turn based on the Silicon Valley lone Genius Myth, which bears the unspoken underlying promise of individual greatness and merits [2]. Damn it is painful to think back to how much self-loathing this delusional belief brought onto myself.
It's comforting to hear other people who share similar opinions about this.
As an independent open source developer, it's clear to me that corporations have taken over open source and have been actively suppressing independent projects.
I've been very fortunate that my open source project was able to get a lot of attention early on (5 years ago) and has been able to get a lot of steady traffic from word-of-mouth since.
I don't know how anyone could independently launch a successful OSS project these days.
I think the problem is not so much with the React architecture, but with the culture of JavaScript, which:
* does a horrific job with documentation
* delivers millions of packages with demo-grade half-finished projects
* has tutorials which show basic functionality, without going into any sort of depth, which people glue together by pattern-matching
That doesn't work well in general, but for something as complex, deep, and, well, architected as React, it doesn't work at all. People really do need to understand reactive programming, functional programming, and deep concepts to handle React well. Resources to do that don't exist.
This is the claim for React's documnetation:
"The React documentation assumes some familiarity with programming in the JavaScript language. You don’t have to be an expert, but it’s harder to learn both React and JavaScript at the same time.
We recommend going through this JavaScript overview to check your knowledge level. It will take you between 30 minutes and an hour but you will feel more confident learning React." source: https://reactjs.org/docs/getting-started.html
Really? Read that again. REALLY? Someone with 30-60 minutes JavaScript programming is expected to code in React?
That's the target audience of most of the docs, and nothing goes far enough to get people qualified to use the tools. It becomes a magical black box. The posts in this thread show this attitude too: "You don’t really need to understand how React works, you just need it to work"
Doesn't sound at all to me like they're saying "read this and you'll be ready to learn React". More like "if you find any part of this overview to be confusing, you might find React confusing."
Also, I learned enough React to be dangerous when I didn't know anything about reactive or functional programming. I imagine plenty of people have had the same experience.
> People really do need to understand [...] deep concepts to handle React well.
"Handling React well" is subjective. What are you building?
> but for something as complex, deep, and, well, architected as React
I'm not sure what "architected" means in this context. But re: complex and deep -
React is complex to the extent that you need to build complex things. It is deep to the extent the developer requires. This is a great aspect of its composable design - it's just components made of components made of...etc.
But people don't learn React by building huge, complex, deep things. They build simple things, and go from there. In this respect, React does a great job with documentation. They start small.
Pretty much yes. I'm a C++ programmer that barely knows javascript that is using React to build a UI for a product. It's complete magic to me and I have no idea how it works. I haven't seen any deep documentation anywhere that would give me more insight that I have now. shrug
For starters, I'd suggest going through Rodrigo Pombo's walkthrough "Build Your Own React" [0], my post "A (Mostly) Complete Guide to React Rendering Behavior" [1], Dan Abramov's treatise "A Complete Guide to `useEffect`" [2], and Shawn Wang's talk "Getting Closure on Hooks" [3].
I also have additional links on both React's internals [4] and React hooks specifically [5] that should be useful.
I use React because it pushes the magic into a well tested library and out of my code. React and hooks are great because they make my code so much less magic-filled.
React is simple it's just a few hundred lines of code, it's easy to understand in an afternoon. Just make sure you pull in a JSX transpiler, and something to do your routing, oh and you'll want something to store your state of course, don't forget that - oh remember to pull in the right version of the transpiler that support decorators for your state management (you do know what decorators are, right?). What do you mean you have a conflicting dependency in your existing codebase? Just fork that repo and upgrade it, that won't take long and cause a bunch of other problems.
I think hooks aren't really making React more of a black box, but just that it's invalidating a lot of people's incorrect mental models on how React works. (It's like C's undefined behaviors in that sense.) And the reason why a lot of people have these incorrect mental models is that React is a very thick abstraction.
For a long, long time, I thought that to provide the values that React brings, the UI framework being a black box is inevitable. Almost all React-esque libraries including but not limited to React, Preact, Mithril felt like a very thick abstraction over the DOM APIs.
But then I saw Crank.js[0], and that felt very intuitive and a thin abstraction, while retaining the good parts of React-esque libraries. I don't really know why it feels like that - I'm guessing it's because it uses native JS features that you already have a good understanding instead of some magic that happens in the React runtime.
I'm very looking forward to it, and I would like to urge everyone to try out Crank.js if you feel that React is now not intuitive enough.
This is the stuff I've counted so far (I know they are not all React alternatives): Preact, Mithril, Crank.js, Hyperscript, Reagent, Closurescript, Elm, Cycle.js, Lit-html, Haml, Slim, Jsx, Meiosis, Svelte, Formik, Vue...
I took a quick look at the docs and I'd say the API looks to be pretty similar to mithril.js. Not sure why you think mithril would have a thicker abstraction in comparison.
>I think hooks aren't really making React more of a black box, but just that it's invalidating a lot of people's incorrect mental models on how React works.
Isn't that exactly the point that the big image on the front page is making? If most people have a mental model of a technology that doesn't match what the company is putting out, it makes very little sense to blame the people who have the 'incorrect' mental model. If it wasn't so widespread, your point would be much stronger. But the fact that the core pieces of react are misunderstood, especially when React publishes documents explaining how all of this is supposed to work and how you're supposed to think about this is an indication that something is wrong with React, not the people who use it.
> If most people have a mental model of a technology that doesn't match what the company is putting out, it makes very little sense to blame the people who have the 'incorrect' mental model.
While you're right that we shouldn't "blame the people", I think blaming the company / library in this case doesn't fly either, given the specifics.
The "incorrect mental model" people have about React is based on two things:
1. the prevalence of OO concepts in programming education and in practice in most engineering teams
2. the introduction of class abstractions onto JS prototypes by the ES spec.
followed by:
3. React bundling things like `createReactClass` and encouraging class abstractions in their docs in the pre-hooks days
While the 3rd point above may have been a mistake on the part of the React team, I do think points 1 & 2 are much bigger factors here.
> something is wrong with React
The only thing "wrong" with modern React is that they're challenging the status quo in popular programming concepts with something they believe is a conceptual improvement.
You can disagree with them on whether it represents a true improvement, but saying they're "wrong" because their conceptual model is a departure from the status quo is pretty reductive.
To put that in context: that was at the time ES was starting to introduce OO abstractions to the spec. and it was somewhat trendy to go in that direction. I never got the impression that the React guys were heavily invested in that paradigm, and they definitely moved away from it very quickly after first encouraging it in their API. Everyone makes mistakes.
As a side-note: I think class abstractions in ES are a feature that in retrospect is less of a great idea now than it may have seemed at the time. ES class abstractions obscure their own subtle issues (in a very similar way to the article's fake Twitter screenshot jokes about React hooks).
- From 2008-2014, _everyone_ was writing their own "class-like" abstractions (see: Backbone, Class.js, five million other "inheritance" libs). So, the React team wrote `createClass` as their own implementation.
- When ES6 classes came out, the React team took that as an opportunity to drop maintaining their own abstraction and switch to something that was actually standardized, and reduce the amount of magic behavior (auto-binding, mixins, etc).
- Function components came out in React 0.14, and were initially limited to just rendering based on props - no state or effects possible
- Hooks now give function components the ability to have state and effects. In addition, encouraging a move away from classes dovetails into the React team's long-term plans for the React APIs.
The class abstractions added to ES spec. didn't happen in a vacuum; it was very much on the back of community demand. Backbone especially had an outsized influence.
Perhaps that was a necessary step toward realising tools to solve problems without those abstractions, I don't know.
Perhaps React is just as complex as it needs to be solve the problems it tries to solve. Is that a true statement? Probably not. Close to true? Maybe.
Whatever the case, just because we wish solutions to those problems were easier to understand doesn't mean reality owes us that. I suspect React in particular, being in the web dev space, has a lot of people working with it who have very little CS background. Because they don't understand how React works under the hood or even above the hood is "something wrong with React"? I'm not sure I buy it.
I've seen a lot of really poor React code that breaks all kinds of best practices, many of them explicitly laid out in the docs. Even before hooks came along. In fact it's been hard to find examples of people who understand the dom well, much less React. I will continue to suspect there's something wrong with most of the people using React, not React itself, which from my perspective has only become better over time.
> has a lot of people working with it who have very little CS background
This and so much this. This applies to "frontend development" in general. I work as a contractor in the frontend space (Europe, no where near FAANG like companies) and very often I meet other "devs" that have basically become frontend "engineers" out of being a webdesigner - like you know, creating nice html templates for wordpress, having decent CSS and photoshop skills and later in their career started to copy-paste some jquery plugins into their template to get nice animated toggles and alike. It is very common in "frontend teams" that people started to get into JS out of webdesign, and have never actually programmed in any other language.
Another issue is even with people with a CS or another STEM background, they only get taught in the "traditional" OOP sphere on top of blocking thread environments. Those usually have a hard time wrapping their heads around higher order functions or async-based development (and to be fair, I also had a hard time when I first encountered it).
Most rank-and-file development doesn't need async and HOF. If your framework does, it's either screwed up or for a special/rare niche. I've been in these debates many times, and when examples are given I can usually trace the "fault" down to the framework or limits of the language. I stand behind this claim.
At least in browser-world, most APIs (i mean the ones defined by the web standards) are built around async/Promise/callbacks/HOF, like it or not. There is no switching to other languages/framework when targeting the browser as a runtime.
Not quite what I said. I said they are not needed for rank and file application (domain-centric) development, IF the tooling and programming language are decent.
If you bring up a scenario, I can probably poke holes in it. Done it many times in many debates. I don't mean to sound arrogant, but I keep winning THIS one for whatever reason.
> I've been in these debates many times, and when examples are given I can usually trace the "fault" down to the framework or limits of the language.
I don't disagree, but my follow-up question with that statement is "ok, now what?"
If you've got a weak/inexperienced developer who's stuck in a framework where they have have to start grokking async/HOF/whatever to solve the problem they've encountered, where do they go from there? It's fine and good to blame the framework they're operating in to be shitty, but they a) didn't have the skills initially to make a solid decision about the framework to use, and b) are now likely stuck with it (unless they're going to do a rewrite with something else).
I agree that our current tooling requires more "rocket science" than it should to do ordinary things. I'm not sure how to fix the entire industry, but the first step to solving a problem is admit there is one.
Early cars were hard to learn, drive, and maintain. Over time they got better via trial and error by manufacturers. The desktop IDE's of the early 90's were like this, but got better over time (until web ruined their market). However, the web is still stuck in 1903: simple things are esoteric. Perhaps because too many other things about "cars" keep changing? Something is wrong. CRUD web dev is a mess.
Most software engineers without a strong background in physics or CFD won't be able to reliably explain how an airfoil works either. Having a wrong mental model (equal transit time of air molecules resulting in lift) does
not mean airplanes are not useful.
The question is not whether your mental model is incorrect, but whether the deficiencies in your model cause problematic consequences. For example if my model of how wings work is that "the slower you go the more lift you get", should I pilot a plane I'd probably end up getting in trouble.
Hooks are fine. The approaching ConcurrentMode though is scary. Most of the global state solutions are suffering from various kinds of incompatibility with the concurrent mode that opens the door to various kinds of bugs:
with concurrent mode i think of what could be, web applications that can compete against native for the first time. as well as making making components that are resilient to async issues / making async a high level concept. there's a little churn for sure (for library devs, and a specific subset), but imo completely worth it.
> with concurrent mode i think of what could be, web applications that can compete against native for the first time
Native apps feel better than web apps because they have robust UI libraries that web apps do not. React concurrent mode will have zero effect on that.
If the argument is "React concurrent mode will make web apps faster so that they feel more native", my response would be to use something like Svelte, which is available today and is considerably faster than React. React is slow.
Concurrent mode may make React faster but it'll just be making up for React's past mistakes, not the web's.
If you have an application that renders more items than Svelte can handle (not many, we're in the web, you have 15ms max per frame, on a single thread), it will simply keel over and die. Scheduling is natural in native systems, you have occlusion, prioritization and threading of course. Svelte has no means whatsoever to counter load.
With what React is attempting currently your app will render as much as it possibly can while maintaining stable 60fps, the rest gets deferred while it can differ between lesser and higher-priority updates. If you doubt how important scheduling is, look at practically any feasible list component, they're all virtualized. With React every aspect and corner of the application is like that. In theory it could outperform native apps.
Btw, there are countless of robust desktop apps being made with HTML: VSC, Whatsapp, Skype, Spotify, Notion, Hyper, Discord, Slack, ... thought most of them will still feel sluggish compared to a native counterpart. React will change that.
That is my point. They are robust from a UI perspective, but none them can compete against native due to the slow nature of the dom. This is why React is building a scheduler.
> countless of robust desktop apps being made with HTML: VSC, Whatsapp, Skype, Spotify, Notion, Hyper, Discord, Slack
VSC: chokes on files larger than several mb
Slack: eats all of your memory, often hangs and just whites-out while I figure out what to do.
Skype: has this app ever actually been good?
Spotify: not sure I'd call it robust, but it's functional...enough.
> In theory it could outperform native apps....thought most of them will still feel sluggish compared to a native counterpart. React will change that.
My understanding is that native apps hook into far lower-level functionality and run with _signficantly_ less overhead. They simply execute faster, and far more directly. I don't see how React and needing to go through react-framework -> JS -> V8 -> etc would possibly compete with that, let alone outstrip them.
These apps all fall flat, which is the point i'm trying to make. They're robust from a design perspective, the tools we have to build UI are good enough, but they can't compete against native. Do you think that using Svelte in any those would make a difference? This is why React is attempting to find a solution.
The problem is essentially the same. Native apps are also conflicted with load, they have better means than we have on the web to deal with it, but it's still low-level and complex to orchestrate, threading for instance. Any one of those means pushes your app into async issuee, race conditions that you need to reconcile. With concurrent mode scheduling is a first class concept, your components won't be subject to race conditions. React maintains 60fps, high-priority content (user input, animations, transitions) can be ran fluidly while lesser priority content gets deferred. It has a good chance of outperforming multithreaded native apps with that model.
This demo illustrates the issue: https://youtu.be/nLF0n9SACd4?t=172 which is universal. You run into this on native platforms as well as on the web.
> not many, we're in the web, you have 15ms max per frame, on a single thread
Isn't the likely way forward to move the computationally heavy parts of the app over to web workers and to keep the main thread almost exclusively for UI work?
After using hyperscript via Mithril, I don't think I can go back to writing JSX. Hyperscript should be the defacto way to template HTML in JavaScript in my opinion, it's just so much cleaner and readable.
It's been the way Elm describes its components; and I believe Andre Staltz has been criticizing jsx in favor of hyperscript since forever [0], and included hyperscript in cycle.js.
Lit-html, which is using template literals, is another good option.
Back when jsx was introduced people said so too but they weren't as loud as the other group. When you look at a completely new language, reasonml where they're still of the mindset that jsx bring familiarity it makes nosense. Just an excuse for some abitrary preference.
I remember getting excited learning that I could do Xamarin Form in plain function calls in F#. Android is going similar journey simplify UI programming with Jetpack Compose. Jsx is backward and purely stylistic.
What is the point of templating HTML? I really don't understand it. Just write HTML or HTML-like APIs like JSX. Is there some theoretical reason why this is wrong?
Subjective I guess. For me it’s just a reduction in noise and I prefer to read code with significant white space. Perfectly ok writing HTML, but given the option, and if it doesn’t screw with others, I prefer not too.
hyperscript is about as close to a middle ground as we can get. It's compatible with JSX for the folks that really really want to see angled brackets, while still being uniform javascript like other API variations (div(), html`<div></div>`, etc). The lit-html syntax is not bad either, but template strings did not have as widespread support back when mithril originally came out.
I've given stewardship of the project to the community. At this point, it's largely in maintenance mode. Most changes are tightening up loose semantics and the like. IIRC the last major was only a major by technicalities; it didn't really break anyone unless they were relying in weird obscure behaviors.
Since the framework isn't interested in chasing trends and since it provides extension points via lifecycle methods, there's really nothing novel that needs to come from the framework itself.
I know some of the more popular frameworks make it seem that webdev is constantly in churn/evolving, but if you look at React for example, other than the hooks paradigm shift etc, it hasn't really changed all that much in scope over the years either (the same can be said about other libraries as well).
For example, Mithril could easily be used w/ coffeescript when that was still a thing, and people use it with typescript these days too without much fuss since TS is also a project that decouples well. And this is with zero changes to the framework. You can integrate dragula or plupload or google maps or whatever via lifecycle methods as you always could too.
So, TL;DR: I think the focus still remains on making it as stable and robust as possible
To me Reagent is the ultimate answer to the markup/code mix. A single language, ClojureScript. Nothing is done in strings except text. I absolutely love it, but haven't been able to use on a production project yet.
I really like clojurescript in theory, but have a dumb practical reason for not being able to use it. I do a lot of programming in common lisp, and am way too used to a lisp-2.
I literally can't write more than 100 lines of clojure without accidentally shadowing a function binding with a variable binding. I think the only way to break the habit would be to abstain from common lisp for 6 months or longer.
I have the opposite issue trying to write in emacs-lisp after doing lots of clojure. I try to:
(mapcar my-func my-list)
and it throws void-variable and then I remember that I have to add the #' reader macro to have it read as a function not a variable.
(mapcar #'my-func my-list)
It just takes some time to switch the mental model over each time. Clojure did get me in the habit of using unique names for all functions and values because accidentally shadowing a function binding is that more difficult mistake to debug.
In practice I haven't missed the flexibility of a lisp-2, if anything it's just made my code more readable because my names are forced to be more descriptive
using hiccup to write html has been a godsend. I find it much easier to visualize the html that hiccup will generate vs JSX, and I can do arbitrary manipulations on it just like I can with any other clojure data structure.
the bummer about reagent is that it allocates so many immutable data structures on render. I've not figured out a way to ergonomically write hiccup without paying this constant performance tax, which is felt on a lot of large reagent apps.
I've done a few projects in mithril, and having used both jsx and hyperscript, I tend to lean jsx.
That comes with some very real downsides - mostly getting jsx to work requires a bunch of extra (ugly) tooling. On the other hand, very complex components look very clean.
Hyperscript when you have a relatively nested dom element gets quite messy and hard to visually parse for me.
It's funny you mention Mithril, because to me, that was the "minimum level of whiteness" box. I tried react fairly early, and when I did something wrong, it was completely unobvious to figure out by debugging the non-minimized code.
Mithril was sufficiently thin for me to drop into the debugger, say "oh, that's how it works" and fix.
I'll take a look at crank though. I do frontend dev only to make my hobby projects accessible to friends and family, so the less to remember, the better.
I cant understand how a developer can be aware of existence of Svelte (https://svelte.dev/) and still have React problems.
Just start with creating web components in Svelte, include them in existing React code, and slowly phase out slow, and old tech that React is. This is just frontend lib, why are people so religious about this. You still use Node, JS/TS, etc.
Im I troll? Don't know, but that is just what I did year ago. Now I just laugh when I see articles like this, buy I also feel sad for small entrepreneurs that have to pay big $ for code in "dated tech" - thinking "they are on the edge".
It's not only that, but there's always dragons in scaling a framework to accommodate teams of hundreds of devs and supporting millions of users. Svelte is less known in this regard. Marginally better along one or two dimensions is not enough to justify the risk.
Svelte is be recommended left and right as the "solution to React" but I think it's still way too young of a project to be the cure-all that people think it is.
It's promising, especially for smaller projects/MVPs, but I still have no idea how well it will scale with app size/team size (and have yet to see good evidence that it does it well).
I just find it ironic that people dog on React for being the "default", but then also can't recommend Svelte fast enough, seemingly because its just "not React".
Svelte is so pleasurable to work with. I'm still a beginner but making my own components that can interact with dom elements (for things like three.js/d3.js/peaks.js) was clear from the documentation almost immediately. I'm in the process of reworking some static sites with Svelte because I can re-use the components I make everywhere and the build pipeline is so simple.
We just tried Svelte in a small project at work, and it was a pleasant experience. Like its small api footprint and closeness to plain html/js and its small bundle size.
In our setup with parcel we didn't get good error messages and line numbers (it spit up internal compiler errors), but it might have to do with our setup. Trying it at home with snowpack it gave comprehensible error messages.
The only two that I'd put on the same level are jQuery and React. And people are still happily using jQuery to this day (maybe happy is the wrong word). So I don't think React is going anywhere for a long time but if something better comes out then why is that a bad thing?
It is more about the relative instability of Javascript as a platform versus nearly any other platform out there.
Skills I learned in college about writing SQL are still relevant today, several decades later. Skills I learned coding for iOS (even Swift!) years ago are still relevant today. CSS and HTML skills I learned decades ago are still relevant, etc etc. Python/ Django knowledge from 10 years ago is still largely relevant. React/ jQuery/ EmberJS/ Vue/ Angular/ Grunt/ Gulp/ Webpack/ Underscore/ CoffeeScript/ etc... damned near every Javascript library I've ever worked on has an extremely limited lifespan in terms of relevance. Even within React, it's hard to keep relevant. Class based React? We're doing Hooks now!
> why is that a bad thing?
It's only bad if you have to try and maintain 10 year old Javascript and in order to do it, you have to learn a whole new paradigm. IMO it's doubly bad right now since so many people are abandoning semantic HTML and more or less rolling everything as their own custom components.
To be fair React is now seven years old. So even in the unlikely event that it’s going to be replaced by something else, the old cliche that the JS ecosystem is always churning too fast seems a bit overblown. It’s on track to be the dominant tool for the best part of a decade.
Well said. Perhaps my deeper point is that hooks and soon Concurrent Mode force devs to come to terms with the fact that they _don't_ understand React internals (hence my usage of black box) and that their mental models were wrong this whole time (although some might argue still pretty productive).
I also think Crank is SUPER interesting on so many levels. I built a few demos with it and am fairly impressed. However, practically speaking (and I'm putting my developer relations hat on), I think its generator API is just too intimidating to junior developers.
I usually explicitly tell devs to not worry about React internals. Let React decide when to re-render or how to batch state updates. React's API is small, developer time is better spent understanding the API than wondering how React works under the hood.
That said it's still a mental shift. Sometimes I feel like I'm writing React and not writing JavaScript.
I noticed at the end of the blog post you stated that you're very excited about the debut of the upcoming Concurrent Mode (CM) in React. I've read about the problem that Concurrent Mode is working to address; but I'm confused as to why React needs this additional feature set when I'm unaware of any other UI frameworks which have a feature set that seem to mirror that of CM. Vue or Svelte do not seem to need these additional features to achieve comparative rendering benchmark speeds to React, and I'm unaware of any holes in these frameworks that something like CM would adequately address. (?).
Is Concurrent Mode basically a way of addressing performance problems in React, or is this in some way a feature that adds something novel? Or is it just a side effect of an unwillingness to move away from functional programming?
I write React at work, but write Svelte or Vue at home, and I've always found React's abstractions to be the most hard to reason about, and from the looks of it CM will make this more challenging (??). Thanks.
Isn't the wider problem that people don't try to understand the internals? Some of us may read the code of modules we "require", but experience tells me this is a rarity.
For those that do, this isn't an issue, and for those that don't, this isn't an issue either. Their mental model may be flawed, but as long as the IO is the same, do they really care?
Concurrent mode isn't really a black box. Its just a shortcut to throw away work that would otherwise be invalidated.
The point of an abstraction is to create a "black box" of sorts around some primitive. I think all it boils down to with what the author is saying is that the React team is changing how things work under the abstraction, and therefore some assumptions people made about leaked semantics are no longer true.
Mithril rendering semantics have always been more or less this: on an event, redraw everything. React semantics started that way too, but now there are a whole lot of other semantics under the hood (for example, the rule of hooks provides some semantic guarantees that enable a hot reload implementation to be more robust). Concurrent mode is another example of semantics that benefit from rule of hooks guarantees.
I think when I see people complain about the rule of hooks is that there's a dissonance between the strict semantics of hooks and the expectations of what the semantics should be (for some definition of "should", usually related to ability to reason about stuff in some specific way)
I'd say that overlapping several different compatible underlying functional semantics under one umbrella of very strict API semantics is an interesting and somewhat novel approach to supporting some cool infrastructure (i.e. ability to do deep hot reloading stuff, animate in IoT devices in a renderer-agnostic way, React Native, granular reactivity via memo, and the list goes on). Where I think React missed the ball a bit is that the API semantics don't always feel ergonomic for the use case they're meant to serve (for example, I've seen a few occasions where nested hooks ended up w/ long code review threads debating obscure minutiae)
When I see people praise Svelte, I think the reason is similar: since it doesn't need to artificially create constraints to support every use case under the sun, its API semantics are able to align very closely to people's expectations.
Crank looks interesting, thank you! I was going to try solidjs[1] (which feels pretty close to crank) in my next project, will look more into crank first.
This is a symptom of a lot of developers thinking they have to write code exactly like everyone else (or at least, strictly adhere to "best practices"). It's a very subtle disease, but I've noticed it again and again over the years.
Reading between the lines, this is a criticism of hooks if they're viewed as a wholesale replacement for classes; from experience I'd argue they're not—they're just a convenient tool for simplifying common patterns. I'd imagine the author knows that to be the case and instead of just using classes where appropriate (or where they wanted), they had to rationalize using hooks because of the aforementioned "but everybody else is using hooks" problem.
I suffered from this behavior for years before I realized it was impeding my work. The term that came to mind for the phenomenon was "The Invisible Developer:" a non-existent developer sitting over your shoulder always judging you for your programming choices. That developer doesn't exist. If instead how "in fashion" your code is is the standard on your team: you're on the wrong team.
That's not a developers fault, that is the insane JS ecosystem. Every year, everything old breaks and everything new is different. Of course no one can keep up, develop intuition and good practices, so all that's left to do is copy. That is how learning works, only the curve never flattens (and nothing is really learned, nothing is gained).
This is true, but even as a fan of hooks, I must admit that you'd be fighting a losing battle if you tried to convince your coworkers to merge your PRs with classes in them, in most places.
That's just the illusion that's created by the inexperience of most JavaScript developers. You don't have to continually learn the bleeding edge stuff. What they don't tell you (arguably, because it doesn't pay their bills) is that what you should learn is the language. Once you understand that, you can comfortably adapt to any new library/framework/whatchamacallit relatively quickly.
Most of what you've described is just peer pressure. The only reason I know that is that I shared this exact opinion until I said "this is stupid" and started doing things my own way (to much success and peace).
Learning the language is one part, but what enables you to make an application are patterns and paradigms: inflating, mvc, mvvm, immutability, functional. These work for all languages, you learn one once, you can apply it everywhere. It just so happens that maybe every 10-20 years a paradigm replaces another. Since i started writing code in the 90s this happened maybe three times. As far as i am concerned all this ever-changing js fatigue talk is complete rubbish. Even the tooling, we're using the same tools that we used 5 years ago (Webpack, Babel, TS, React, Jest, ...). Microsoft/Apple change their platform toolkits quicker than that!
Class lifecycles being replaced by hooks is a radical but much needed change. Learning it isn't complicated and it will enable you to venture on as everything around you sheds the class based component approach. Swiftui, Vue, Svelte and ofc React are just the beginning.
> Once you understand that, you can comfortably adapt to any new library/framework/whatchamacallit relatively quickly.
I disagree. If you know typescript, it's still quite a leap to be able to code with angular, and debug weird stuff where you stare at a blank page, and the back trace in the dev tools include not even a single line of code you wrote.
Also, the language isn't really enough. You need to be familiar with the tooling (npm/yarn, babel, whatever) to use most libraries; so unless you do everything from scratch, you have to deal at least with the churn of the toolchain.
>Every year, everything old breaks and everything new is different.
It's great for online educators and others who monetize devs though..
The JS ecosystem almost seems like it's self promotional, where the monetization opportunities result in a higher self marketing activity of individuals on platforms like Twitter, which of course builds up hype and draws more people into it.
I get so tired of the churn claim. Let's look over some stuff
ES6 -- 2015
jQuery -- 2006
React -- 2013
React Native -- 2015
Redux -- 2015
VueJS -- 2013
6to5 (now Babel) -- 2015
Webpack -- 2012
ESLint -- 2013
jslint -- 2002
ExpressJS -- 2010
Lodash -- 2012
UnderscoreJS (basically the same API as Lodash) -- 2009
D3 -- 2011
Blockly -- 2012
Node Red -- 2013?? (I'm not sure when IBM first released the project)
Bootstrap -- 2011
PDF.js -- 2011
WinJS -- 2012
SocketIO -- 2012
ThreeJS -- 2010
dotenv -- 2015
momentJS -- 2011
node-sass -- 2012
Winston -- 2014
yargs -- 2011
Modernizr -- 2009
Jasmine -- 2010
Mocha -- 2011
Jest -- 2015
All of these are at least 5 year old and most are 8-9 years old. Look over the most downloaded npm packages and you'll find this to be generally true for all the top packages.
That's an example where, when you jumped on the bandwagon at the height of the hype, you were thrown into a backwards incompatible rewrite pretty quickly.
And while npm has been around for quite some time, my outsider impression is that was, for some time, basically discouraged from use, because yarn was so much better.
Compare that to Ruby on Rails -- 2004, Catalyst (Perl) -- 2005, Django (Python) 2003.
Time moves slower in enterprises, with upgrade cycles more on the scale of 3 to 10 years.
Angular 2 shared a name for marketing reasons, but was/is 100% unrelated as every major idea in Angular turned out to be bad.
Yarn solved some npm issues they refused to tackle, but npm got motivated and has now solved most of them. Meanwhile, yarn 2's release has been a disaster and has seemingly resulted in most people (myself included) moving back to npm.
I've done Rails and Django work. Rails in particular took years to migrate to the next version. I'd add that Rails has seen 6 versions in 16 years which gives around 1 major breaking upgrade every 3 years (in truth, there's been about 1 major change per year as point releases are pretty big). Likewise, wikipedia gives almost 20 major django updates (I haven't used it in several years, but point updates used to have a very big risk of breaking the project I was working on).
> Angular 2 shared a name for marketing reasons, but was/is 100% unrelated as every major idea in Angular turned out to be bad.
Be that as it may, Angular 2 meant nobody was willing to commit to any fixed time span to support Angular.js, so it basically forced everybody to migrate off of Angular.js, introducing the toil and churn we were discussing.
Quite a few of these packages have undergone significant backward-incompatible changes over the years and are intertwined with specific version ranges of other packages. The churn complaints are caused by the cadence of this happening and how difficult it is to stay on a combination of stuff that actually works together. Babel may have been released in 2015 but nothing written back then would work in babel today. Same with webpack. I can't write something and then come back in a year and expect even an ounce of stability in my project. It's good that things keep improving but it's also exhausting having so much time spent performing upgrades and re-learning best practices in tools you were previously comfortable with.
There is a real pressure from the ecosystem though. When looking for a library there is good chance that anything recent is written with hooks in mind, and the examples are primarily hook based and the issue tracker is full of questions about hooks... so while you can try to alter your own behavior it feels like you're swimming against the tide.
See my reply to _stefan above (responding to the need to use something out of necessity for lack of alternative).
In respect to swimming against the tide, this is where experience comes in and knowing both how and _why_ something works the way it does. Over time, you can develop your own opinions and not have to worry that much about what everyone else is up to.
Admittedly because I mostly work alone that's a privileged POV of sorts, but I think teams can "act as an individual" and adopt a similar attitude (scale of team permitting).
I, for one, do not mind developers adhering to some common patterns/best practices. Whenever I open a codebase foreign to me, I bank on those patterns to understand the app to be able to contribute, learn, etc. Seeing new patterns would be helpful to myself, of course. But, there's a good chance I would bail out if I don't have a huge need learning that codebase.
Hooks do draw you in the direction of a wholesale replacement just because of their incompatibility with classes. I wouldn't consider that to be a bad thing but it does take some time to adjust to the change at first.
I'm an Android developer who despises Kotlin, reactive programming, and "the Google way" in general. My main gripe with all this is that it needlessly complicates everything that can already be done in Java with vanilla SDK. All these additions are touted as a way to write fewer code and do it faster, but the problem is, it's all rather complex under the hood and requires you to hold a lot of context in your head at all times. And if you want to read someone else's code, you gotta have the encyclopedic knowledge of Kotlin, because characters are apparently a dollar each and it's not like we can spare some to write code with actual words people can search for. And to make it even worse, "the Google way" is a moving target. It's constantly evolving just for the sake of change.
In the end, I'm sticking with Java and vanilla SDK because it just works and only changes ever so slightly with each major OS release. Also my apps run pretty darn fast on 7-year-old devices because they only use the CPU to do useful work.
I find Kotlin more readable than Java in most cases -- less noise to drown out the actual logic. Could you provide an example of a language feature which requires you to "hold context in your head"? It's possible that you have just worked in bad codebases abusing Kotlin sugar. Inferred types for example can improve readability, but only if the variables are named appropriately.
> Could you provide an example of a language feature which requires you to "hold context in your head"?
Extensions. Basically every project has its own dialect of Kotlin that you have to know everything about if you're to understand anything. And good luck doing that without an IDE.
> It's possible that you have just worked in bad codebases abusing Kotlin sugar.
I've never actually worked with Kotlin, I've just seen many examples of it. The problem is, the language itself pushes the developer to use all the sugar, and they have to control that themselves. As opposed to Java, where writing unreadable code would take extra effort because of how dumb and simple the language itself is.
Also, to me it feels like an abstraction on top of Java that gets in my way as opposed to being helpful.
Exactly. I wrote this in another comment but I've been following a Github issue about hook support in Flutter, and I understood React hooks much better after reading that than I ever did before. It is clear now what exactly the problems hooks solve are, composable life-cycle state reuse. I think that because most people don't really understand why hooks were even needed, they can't wrap their minds around them.
From my ultra naive perspective - this was always the case with me.
At the very beginning, Virtual DOM manipulation/management was beyond me. Then they updated the engine to React Fiber. If I thought I understood anything under the hood, I really didn't then.
I believe the author is talking about tiny unexpected side effects as a result of the complexity. Like on a particular hook, 1+1=2 out to 7, 9's. But if you do it just in the right way, you'll get a weird side effect (i.e. 1.0+1=3).
This is a typical result of being a ultra power user and I feel the author's pain.
FWIW, I don't think being a black box is bad. Kernels are black boxes, CPUs are black boxes, to so many of us anyway.
The spirit of what the author is trying to make is - this black box isn't completely predictable. It's only mostly predictable - it needs to get better so everyone can rely on it.
I do not envy people struggling through the adoption curve of using Hooks. I don't know enough about them to know how to "fix" them, nor do I have the time to care about that problem - but I would love to see a different syntax, abstraction, or some kind of guard rails around them.
I might be wrong, but it has always felt like scope & hoisting are the primary language features that hooks operate on... both features that I prefer to avoid.
Adopting them seems to require the same leap of faith that is required with something far more complex like early angular versions. The "I don't get it but I'll just follow the rules" kind of vibe... But the web community seemed to understand and fall in love with Rx a few years ago, so I'm sure hooks can become more well understood, too.
"becoming" - it has been since the beginning. You have to import the react library or it doesn't work. You create classes but never instantiate them. JSX is invalid JavaScript syntax. It's a veritable cornucopia of black box features, with hooks being just the latest.
But most of those are easily understood the second you say "Babel is going to take the JSX, convert it to javascript, and expects React to be there." Is that crazy? Sure, but it's also pretty easy to update your mental model for.
The most telling thing about hooks to me is that I need a library just to use intersection observer, because the way you have to implement it to replication the same 5 lines of code from vanilla js is so much more complicated.
Pure functions with clearly defined type signatures are always preferable, in my opinion, because there is far less thinking involved. Elm's vdom is done in this way, as is the vdom used in PureScript Halogen.
React is great, and groundbreaking, but with 20/20 hindsight, there are better ways.
It has always been a black box. Not a single one of the people I've worked with over the past four or five years could understand or explain even a fraction of React's internals. Reading the source is a massive undertaking. Of course not every dev has to know the the tools inside out, but it was not unusual to discuss the inner workings of Backbone / MooTools / jQuery / etc back in their day and I think that made all the difference. We have Preact, Riot, Svelte and many other options that are much more accessible, pick one for your next project :)
One of the things that I don't like about React applies to maybe all frameworks. It's easy to get 90% of the way there, but the last 10% is the hardest. For example, I'm building a real-time websocket app with React. Everything seems pretty easy to build, I'm using hooks, React Router, etc. But coordinating socket connections / reconnections / etc and fitting it into a very functional paradigm is just very very difficult, much more than it would be in a more straightforward library.
For that kind of thing, rather than tightly coupling it to your React tree, you should have components that sanely handle each possible state (no connection, connected but no data yet, new data available, stale cached data available, etc), then have separate handling for the socket stuff that updates data via a global store like Redux.
It is true. Full disclosure - I'm very inexperienced when it comes to javascript - it is on par with my German skills - I can do basic shopping, order a coffee or get a bus ticket, get from A to B but that's it. But I do feel like it's been a black box by design from the start. At the end of the day, we are talking about transpiling code. Which is fine(depending on the definition of transpiling to begin with). If we look at how C affected Assembly, there's no question that the appearance of C skyrocketed the entire CS field in general: Even the most basic of "hello world" programs is a testimony of that. At this point Assembly is in the Cobol universe - a handful of people know it to an extent at which they can work with it. But in the case of React... That really isn't the case - the fundamental problem I see with React(and the entire NPM universe for that matter) is that they try to make a simple solution more simple by making it more complicated and convoluted. On a more general note, the web is broken. It has gone against it's core principles and design. HTML was meant to serve readable documents and that's it. Javascript's purpose was to add some interactivity. But in this day and age, according to reacters anyway, HTML is pretty much Assembly or Cobol, while javascript is C. Which in theory sounds great as far as the analogy goes but in the real world, javascript's purpose was never to take over. It's purpose was to supplement. The flaws in React(and all other 5000000 frameworks) are a symptom of it, not the cause.
I know almost nothing of React but this looks eerily similar to the (in-)famous Drupal hooks. Back in 2005-2006 there were articles like this [1] which were mostly caused by people not understanding (or mis-understanding) how the hook system was supposed to work.
React was always a black box, more or less. To me, what happened was the React team decided boilerplate was worse than cognitive load and the appearance of simplicity, and changed the framework accordingly.
Class components are easy to understand and reason about (mostly) - but they result in a lot of boilerplate code for simple functionality and event handling. Hooks, to me, are the opposite. They have all kinds of limitations and footguns which you need to be aware of (yes linters help) but they give the code a much cleaner appearance.
I personally prefer obvious boilerplate over clean aesthetics but I know lots of people who prefer hooks. I've sinced moved to Preact and have not missed real React once.
I'm not sure if I would describe it as boilerplate because it includes very real cognitive overhead. The best example is the lifecycle methods: if you access a prop in componentDidMount you need to remember to handle what happens if that prop changes in componentDidUpdate. It was incredibly easy to write broken components using the class API and much harder with the hook API.
The most telling difference after starting to use hooks when working with both junior developers and more seasoned ones is that code that seemingly (and intuitively) behaves in one way actually does something slightly different, or worst case - something entirely different. Most often the culprit is a combination of the hooks themselves, the rules and the more general issue of the dependency array and lack of built-in immutability in the language.
This happened before hooks as well, but the class syntax and lifecycle methods felt like a thinner layer on top of JavaScript. Hooks is a much more proprietary concept that tries to solve a much wider problem - having stateful functions, except they make no sense outside the realm of react as they exist right now. Maybe some form of implementation using generators would bring it closer to the language, but that would most likely introduce it’s own set of challenges.
Don’t get me wrong - I enjoy working with hooks, but it just doesn’t feel quite right that they are so tied to some «magical» implementation that requires a large set of rules to behave as expected. It helps to look into the implementation, and especially to reimplement a simple version of react with hooks yourself - but that’s just not a realistic option for many.
Kudos to all the innovation coming from the React team and community though - I’m sure they think about this stuff all the time.
Well said. I like the idea of generators if possible, but have no idea if it actually is possible.
> they are so tied to some «magical» implementation that requires a large set of rules to behave as expected
100% agree here & with your sentiment about the Class API
I tried this, and it's possible using a monadic interface. Just like replacing promise.then with async await you can replace monad.flatmap with generator yields. But I've already seen this concept discussed by the react team and it seemed they didn't like it.
What's cool with a monadic interface is that you can create lots of other interesting things, as long as you adhere to the interface. For instance, I think it's possible to achieve something similar to async render functions without specific support for it.
> Maybe some form of implementation using generators would bring it closer to the language
That's what https://crank.js.org does. I haven't tried building a real app on it yet, but I have to say it does seem pretty elegant and promising at a first glance.
I highly recommend this talk (first half) for a great introduction of how React Hooks work internally, Ryan remakes the basics of hooks from scratch in 30 min:
I agree on 2 of the points of Jared Palmer but disagree on one:
- [agreed] The new "Concurrent Mode" will take things to a new order of complexity. I am actually very afraid of this, it seems like one of the things that might actually kill React, and I love working with React. I like it so much that I've invested into creating few React libraries to make my life easier.
- [agreed] React Hooks are difficult to get started with and to really understand them. IMHO this is mainly due to "React lifecycle", which is just a difficult concept (even with classes!). Life is not easy, and there are some times that there's complexity and you need to learn new complex concepts. No issue here IMHO.
- [disagree] React Hooks is currently magic. While it's a complex piece of software with many small details, once you understand fairly well the lifecycle (and React docs are great at this, and Dan Abramov's https://overreacted.io/ digs a lot deeper for the curious) all bugs are very clear.
I am currently mentoring someone in React who already knew HTML+CSS+JS, my recommendations are: get used to the syntax by practicing, learn the 3-4 typical libraries, and learn very well the lifecycle including how useState's setState and useEffect's dependencies work. That's most of day-to-day React work.
I've been following a Github issue about hook support in Flutter, and I understood React hooks much better after reading that than I ever did before. It is clear now what exactly the problems hooks solve are, composable life-cycle state reuse. I think that because most people don't really understand why hooks were even needed, they can't wrap their minds around them.
...That doesn't clear up a whole lot for me. Keeping in mind I know React but not Flutter (there may be details that make this inaccurate for Flutter):
> Reusing a State logic across multiple StatefulWidget is very difficult, as soon as that logic relies on multiple life-cycles.
The logic should be inside StatefulWidget, and StatefulWidget reused - so no code duplication or hooking into the parent's lifecycle methods.
> A typical example would be the logic of creating a TextEditingController (but also AnimationController, implicit animations, and many more).
Looks to me more like TextEditingController should be turned into a stateful component so it can be reused in the render - this lets the framework handle its lifecycle and none of the boilerplate is necessary. I've done this a couple times with variations on AnimationController: It uses React.cloneElement on its children to pass down the appropriate state, and because it was itself a component that simply rendered its children, React handled all the lifecycle stuff within that component with no hooks to the parent.
I can here kinda see where it's coming from, but we've never had reason to use hooks like that, so I guess I just don't see it as as much an issue. Also, a very important part of it that some other comments over here seem to not be aware of:
> In practical terms, there are a few things here. First, it's worth noting Hooks aren't an "extra" API to React. They're the React API for writing Components at this point. I think I'd agree that as an extra feature they wouldn't be very compelling.
The problem arises when you want to reuse a lifecycle function in multiple Stateful or even StatelessWidgets. For example, if you go to the bottom of the issue, I make an example where I needed to have an AnimationController with complex initState and dispose methods. With hooks I could encapsulate all of that and make it work with any Widget I wanted, I didn't have to rewrite it each time.
There are a lot more examples, it is worth going through the entire ~250 comments, even though it may take some time. I only understood after doing so, not necessarily by just reading the initial post.
This is exactly correct and a large driver of the problem for me. React Hooks eschew solving the problem I really care about (shared state) in favor of solving the problem I don't care about 99% of the time (shared life-cycle). On top of that, the API is terrible - magical extra args, stale closures over state are baked in, and using a hidden index to track call order so they can't be used in branches or loops!? I have never written a hook correctly on the first try because the behavior is too unpredictable/subtle.
Our team has seen a boost in productivity thanks to hooks. It has resulted in more straight forward and cleaner component code, making it easier to reason about how they work.
We've been able to get rid of a lot of annoying and confusing stuff when working with class-based components (though perhaps not all of that was related to hooks but also due to early React boilerplate/tutorials which may have proposed things which are now considered bad practice even with class-based components). No more componentDidThis componentWillThat but a simple effect api (the cleanup function can be a bit confusing at times though). No more unclear setState calls but clear and logically separated state updates. No more class method callback binding hacks but simple functions. No more `this` confusion. No more "Pure" and shouldComponentUpdate confusion but a simple memo api. No more weird Redux 'connect' biolerplate but a simple select and dispatch function.
As far as our team is concerned, React has always been a black box and it has helped us a lot being productive. Perhaps it has become harder to reason about how React itself works, but it has definitely become easier to reason about the components built with it.
Can anybody offer a friendly explanation to me as to why it's not wise to update the DOM directly?
I understand that React is supposed to be an efficient and "ergonomic" way to develop for the increasingly complex array of devices out there in the world, but I have had too many poor experiences with React to consider it better than direct UI programming for my needs.
One of the motivations for using a virtual DOM as opposed to updating the DOM directly is that DOM updates can be slow, with a minimum duration per change. Applying changes to a virtual DOM can be faster for individual changes, and then those changes can be batch-applied to the actual DOM, minimizing the number of changes to the DOM itself. For larger client applications this can be a win. Like all trade offs, the choice depends on the context.
Neato, so then much like an enterprise service bus (ew old term), there is a bus that comes at a rate of x hertz that events can be loaded onto, and the bus has a certain capacity for events. The busses then load events from the event queue and when it reaches the client, they're all rendered at once. Sounds cool. I guess this is what all of the componentDidMount and componentWillMount is used for?
If that were true how would virtual DOM ever be faster than the DOM? It would still have to update the DOM itself.
What V-DOM is trying to address is tracking what is changing in your application so that it can modify the DOM on your behalf, simplifying app development and reducing bugs, sort of like how a Garbage Collector manages memory for you and gives you similar benefits.
Look at Svelte, it doesn't have a V-DOM and it smokes any V-DOM framework in terms of performance.
> If that were true how would virtual DOM ever be faster than the DOM? It would still have to update the DOM itself.
It uses a very smart algorithm to diff two vDOMs (previously rendered vs. newly rendered) and "calculates" a minimal* set of operations required to get the current DOM (=prev. rendered vDOM) into the new state of the DOM (=result from current vDOM render).
Think in source code patches produced by tools like diff: A patch between two different code tree versions can fit just a few lines and is quickly applied against the tree, while shipping and writing the full tree is more expensive.
*: ideally it would be minimal in a sense there is no smaller/faster representation, but thats of course not the case in real applications.
It's perfectly fine to update the DOM yourself. The problem is really that hand writing the vanilla code to do that will be tedious to say the least.
Svelte is essentially that. You write simple components. The compiler checks the dependency graph and converts your code into the vanilla code that would be needed to render those components and make the necessary changes when you modify a reactive variable.
That's why Svelte apps are much faster and smaller. You also write a fraction of the code compared to React/Vue/etc which I think it's actually the best part about Svelte.
> Can anybody offer a friendly explanation to me as to why it's not wise to update the DOM directly?
Sure! The fundamental problem that React solves is turning some canonical notion of state into the DOM (with an eye on composability). This is the central problem of web dev. Once your application grows large enough, you will inevitably end up re-implementing a much worse, ad-hoc solution out of $ or innerHTML. You will build your own React and will be responsible for maintaining it! If the scope of your app is small any solution OK.
I'm speaking from experience: I have built several Reacts over a decade or so - so before it existing and a few afterwards.
378 comments
[ 4.6 ms ] story [ 285 ms ] thread> (informal) a complex system whose internals are not easily understood.
So what the article author does not understand of React internals? I don’t care about React internals either until the API is well written and easy to understand. Hooks did not go in this direction :)
In fact, it smells like the author doesn't know what he's talking about; in my experience "That will break for the following incredibly subtle reasons:" is usually about React fundamentals such as being deliberate with state mutations.
Custom hooks are some of the most useful and fun code to write, in my experience.
If anything, React is becoming less of a black box, with a 'simpler' API. It's just that in the process to moving to or learning the new API, people are understanding they didn't actually understand React before. They're now being made to confront that.
You can disagree with him fine, but I'm quite sure the founder of Formula knows what he's talking about when it comes to React.
I've only touched that package a few times since but it never fails to make me wish the original lead hadn't used Formik. I dunno, forms in react have never given me tears, but contrary to Formik's slogan it has been painful, even aside from this versioning fiasco, so I'm not sure this endorsement is as strong as you think it may be.
What I'm saying is silly is to say the author is somehow "uninformed" when it comes to React like he's some sort of newbie, as opposed to the guy who wrote the library that a sizable percentage of React apps use for their form components.
The author is Jared Palmer. He's a well-known engineer who has worked with React for years, and the author of a very popular OSS React library (Formik).
I used Formik long before hooks, then later, after hooks. I remember hesitating a few times because some of the exceedingly neat pattern/syntaxes were impacted negatively by hooks.
I still "happy" with both, but my team is all quite senior and I feel for jnr teams trying to grapple with React AND hooks at the same time.
I've read a lot warnings about the pitfalls, and about hooks not doing what you think they are doing, but honestly, I haven't experience any of that, maybe because my use cases are so close to the documented ones, that I don't need to stretch the concept, and it just works as intended for me.
Could it be, that as with many other programming patterns, some developers are using it as a silver bullet, and trying to solve everything with hooks?
Otherwise I'm failing to understand, it would be useful to see examples as the mentioned above.
On the one hand, they are nicely composable. You can make one hook call depend on another and you can easily build a lot of cool functionality thanks to this. On the other hand, you are no longer able to directly follow the flow of the code. Making a change to a series of hook calls can sometimes be scary to me as it can be hard to fully understand the cause-and-effect of that change.
On the one hand, you can hide a lot of complexity behind a simple `useSomething()` call, on the other hand the code inside `useSomething()` can be absolute horror, because all the stateful logic is handled through hooks. Any non-obvious use-case ends up being a mess of hook calls. If you only write the code once and never need to touch it again, `useSomething()` can be an amazing hook though. There are some hooks that I have written that I hope I (or anyone else) don't ever have to touch. I might just be a bad programmer though, or missing some obvious patterns.
TLDR: hooks work well, but they have downsides in terms of maintenance burden
If you need to make such statements something is very wrong. Either your code or with the design patterns you're forced into by your framework/library
Hooks are, at least as they're presented on the surface level, exceptionally functional, so shouldnt it be easier to directly follow the code? Just follow the function calls?
> Should I use Hooks, classes, or a mix of both? [0]
> When you’re ready, we’d encourage you to start trying Hooks in new components you write. [snip]
> Do Hooks cover all use cases for classes? [1]
> Our goal is for Hooks to cover all use cases for classes as soon as possible. [snip]
The answer about higher-order components is a little more nuanced but does say hooks should replace most of them:
> Do Hooks replace render props and higher-order components? [2]
> Often, render props and higher-order components render only a single child. We think Hooks are a simpler way to serve this use case. There is still a place for both patterns (for example, a virtual scroller component might have a renderItem prop, or a visual container component might have its own DOM structure). But in most cases, Hooks will be sufficient and can help reduce nesting in your tree.
Learning enough about the React lifecycle to make simple apps was a big task, but it felt like a bounded one for my purposes. Learnings hooks seems... strangely open-ended. There's a small set of built-in hooks that do certain things, and if I need more I'm supposed to build new hooks out of the old ones, and that's supposed to be it. Except that it isn't, because if that's all there was to it, people wouldn't be having difficulty. I just wish the rest of the story was sketched out and bounded for me in some way so I could know what I was getting into.
I remember people having difficulty with callbacks, then with generators, then with promises, Obersavables... you get the point. There is always something new that tries to make 80% of the cases trivial with a new elegant syntax that hides a lot of complexity, and comes with that 20% of cases where it is harder to grasp.
- said it was bad
- not provided any concrete details
> they've become unmaintainable when reaching a certain size
How?
Did you start getting lot of hard to replicate bugs?
Did you find authoring new components was made difficult by your heavy use of custom hooks that were actually not as generic as you thought when you wrote them?
Did you find 3rd-party hooks had bugs?
Did you find that useRef doesn't work like you think it does, and you can't mix and match useRef and useEffect? (ouch)
What kind components are you writing that you find hooks are such a bad fit for?
Be specific.
(I'm not saying hooks are perfect; I've had all of the issues I listed happen to me, but it's still quicker to implement new features on a medium sized web app using hooks than with components in my experience; I work on 3 apps, and only one of them still uses components, and it's the most annoying to make changes too, simply because for simple business components & forms, hooks seem to reduce the amount of boiler plate, and flat out, reduce the lines of code; less code -> faster changes. It's not always that simple (see bugs comment above), but mostly... it is, in my experience: ...HOWEVER, what you've done is just wave your hands vaguely and fail to actually say anything except you don't like hooks)
One of my favorite papers on it: https://github.com/papers-we-love/papers-we-love/blob/master...
How complex it is is not relevant unless it has a tangible impact.
eg. I use spark a lot. I don't really deeply understand how the DAG is translated into a distributed computation and the results are aggregated from the cluster.
It calculates things. It's fast. Sometimes I'm surprised by things that are slower than I expect. Oh well. Don't do lots of column renames. /shrug
It's a tradeoff.
Is the effort to understand the detail worth the benefit of doing so? Does not understanding it cause enough pain that it become prohibitive to develop using it?
Is it for spark? No. I really don't care how it's implemented. I don't even know scala. It works fine.
Is it for assembly? No. I don't care at all how my code is JIT'd to assembly / code. It just works.
It it for react hooks? I honestly haven't personally found it to be... but I don't write custom hooks much.
So, your experience with hooks might be different, and you may find the trade-off is more expensive if your case, because it tangibly causes, eg. bugs when you write your code.
...but you are quite wrong if you think that not understanding how something works is a fundamental obstacle to using it.
That is categorically false.
I would argue that it's far from proven that using complex systems necessarily causes the complexity of your system to balloon out of control... or that there is even a strong casual relationship between "mental model being complex to grasp" and the resulting complexity of the system.
Thats the point: the mental model is irrelevant unless it causes bugs when you use it wrong.
Does it? Does it actually cause bugs?
Not, “in general”; You’re just doing the same thing again here and doing vague hand waving. What actual bugs? What types of bugs?
Be specific
(yes, it does cause bugs, but see how this conversation is pointless when you don’t provide any details? Right, now go read the first post in this thread.)
All of sudden, the magic stops and you have to deal with a ream of obtuse stack traces, problems that completely smash your metal model of what's going on, and you end up in deep rabbit holes of stuff you don't want to get into at the worst possible time. That is a fundamental obstacle.
With hooks however, you can create self-contained custom hooks that group all the code of a feature in one separate file. It's much easier to test and to make sense of. It's also easier to make the hook more generic and re-usable when it becomes needed by other components.
I'm definitely not going back to class-based components as I find React hooks a lot easier to manage and maintain.
Sometimes when I read these comments I feel like I am using a completely different library.
If you push me by asking "why?", I can expand that sentence by including "because each hook call is associated with an index under the hood".
This is probably the only React hook nuance you really have to understand, and it's not particularly difficult.
There's nothing stopping someone from reading the explanation in the React docs[0] if they want to understand.
[0] https://reactjs.org/docs/hooks-rules.html#explanation
Absolutely not. There is the dependencies array, how it only does a strict equals check (no shallow comparison), how you need to memoize other dependencies so they don't change on every render, why it is a problem to leave it empty, why useEffect cannot strictly replace componentDidMount, why you can't put one hook inside the other, how (and which) hooks can trigger a re-render or block updates, how state is captured by the closure and what to do if you need current state, how to persist things across renders using useRef.. and probably more.
Edit: That was snarky, I apologise.
2. But it runs a bit differently sometimes: const [a,setA] = useState(1234); Here "a" will have the value 1234 on the first run (what is a first run? When react instantiates this component? When it mounts?) Then this same line of code will assign a different value to this same variable, because setA was called in the past. Why? How does it know that this exact local variable needs a different value?
2. Before calling your render function, it stores a reference to that object in a private, global variable. (Global in the sense that there's only one per JS VM) (Javascript is single-threaded so this is perfectly safe to do).
3. Each of the built-in hooks has access to that variable, and use it to increment a number representing the current hook index and then store information in an array at the current index.
4. The next time your component is rendered, that information is still there and the hooks can retrieve it.
5. Also some hooks like useEffect set up functions to be called by react later.
I am working through this exercise now, but I'm already finding myself doing some pretty hacky things to make this work (like finding out who called a function using arguments.callee.caller.name). Still, it's pretty interesting.
Edit: My solution to this: https://gist.github.com/rashkov/f765917d09ebd629f385c21195f4...
I was mainly interested in solving for how React lines up the useState calls with the actual data that it's keeping under the hood. So I definitely cheesed through the parts touching on how React keeps track of the component tree. I'm enjoying reading through your interpretation of this though. Thanks
Render functions are only called when a component is being rendered. React keeps track of which component is currently being rendered. When you call `useState`, React knows which component is currently being rendered and keeps track behind the scenes which state that component has.
The way it knows which value it should return for `a` ties directly in with why you need to call `useState` calls in the same order -- React basically keeps a list of the state behind the scenes, and returns the (secret behind the scenes) state in order. If you change around the order of `useState` calls, it can't use the ordering of the calls to determine which state needs to be returned.
<div> {isLoggedIn ? <LogoutButton /> : abcd } </div>
and I change the value of isLoggedIn. Does the state reset? I'm not asking for a solution, just pointing out that even a 'simple' hook like useState has its small quirks.
This is the same behavior as has always existed with class components and `this.setState()`. Component-scoped state only exists as long as that specific instance of the component is mounted.
So basic memoisation?
> why you can't put one hook inside the other
Hooks inside other functions may be called at any time, how is React to know which component is calling them?
No. Before you just had to worry about shouldComponentUpdate and data received from the 'outside'. With hooks you need to memoize arguments to every function you call within the component - you didn't have to memoize class methods. The concerns and patterns involved are very different.
Why would you call a hook inside a loop anyway? Hooks return callbacks and variables, which you can use inside a loop without problem.
[1]: https://reactjs.org/docs/hooks-rules.html#explanation
In fact the linter explains exactly that in a paragraph:
> React Hook "useState" may be executed more than once. Possibly because it is called in a loop. React Hooks must be called in the exact same order in every component render.
https://reactjs.org/docs/hooks-rules.html
They'll say something and I'm wondering "what do you mean exactly..." but we don't know.
I get how folks might not want to get into the weeds on minutia or etc. But without examples it's hard not to think someone just doesn't 'get it' too.
I'd much prefer the latter, but it seems that links are the way of websites such as these.
1) React solution will need a little bit more lines;
2) There are multiple ways to write that and some ways are less efficient than others;
3) React solution is harder to write if you only started with hooks.
I'm going to use React because:
1) I don't need to learn anything new (only hooks) to do what I need;
2) I have richer environment: typescript, testing libraries and all React libraries/solutions I might need. Svelte is getting better and potentially it already covers things I need but that was not the case one year ago.
> Remember that React is supposed to take care of the “how” so that we can focus on the “what” of our apps. This mantra though, assumes that we can predict the “how”-part correctly.
Their claim is that it's becoming increasingly difficult to predict how React is supposed to work in different scenarios.
"Black box" means you don't know what happens INSIDE the box. A very succesful software abstraction might be a black box, this isn't generally considered a negative in software. A good "black box" is completely predictable from it's interface, even though you have no idea what's actually going on inside of it.
To me, "accessing disk IO" is a "black box", I have only a vague idea what happens inside the black box when I ask to read or write bytes; and I don't need to, because it works reliably and my very simple mental model of how it works serves me. (If I was doing realtime or high performance or something, I might need to go inside the 'black box', making it no longer a 'black box' that you can't see inside, but I am not and have not).
Wikipedia: "In science, computing, and engineering, a black box is a device, system or object which can be viewed in terms of its inputs and outputs (or transfer characteristics), without any knowledge of its internal workings."
But that's not actually what OP is talking about.
The author is not actually complaining that it's a "black box", he's complaining that the inputs and outputs of black box are too hard to understand, that the mental model of what the black box does is too complex, that it's no longer predictable what it does.
This article might get upvotes because people agree with that basic conclusion, it matches their experience. But it's a pretty poorly written article. It has no examples or evidence, and it's central point is poorly expressed using the wrong terminology or metaphor.
Simple CRUD-like thing? Why would you reach for a front-end framework such as React to build it in the first place? Ideally, React should be used to solve sufficiently complex problems.
First, definitely lacks a historical perspective. The React team is certainly not new to accusations of banking their platform on certain mental/implementation/stylistic decisions which people REALLY scratched their head at, only to then become the behemoth of a framework that it is. JSX???? CSS and JS in the same file??? Etc.
But more importantly, this completely overlooks the amazing work the core team has done to make sure you DO NOT NEED TO TOUCH ANY OF THIS STUFF AT ALL if you never want to. React powers one of the most complicated and widely available web apps in the world. That the company and team building it are including tools and philosophies which feel awkward for your CRUD app should simply feel... right. But what certainly doesn't feel right is to see the core team build out more and more features, which support more and more advances and highly specialized use-cases, only to then see the community turn on them somehow because it is "too complicated" or a black box.
> I think a good ol’ Pete Hunt-style “Thinking in X mode” blog post would go a long way.
They point out that maybe all that's missing is a simple explanation of the thinking behind the new React features is, much like React and its developers did when they first introduced ground breaking features.
Not sure if you can blow more smoke up Zuckerberg's ass?
I feel like we need a new word: 'trickle down software' (in the pejorative sense). It recognizes that the corporatocracy has plundered the Commons/public domain [1], and are 'gifting' us frameworks like React while keeping the most useful strategies and mission critical frameworks and strategies for themselves.
Maybe I should just stick to campaigning for 1) Protocol Cooperativism using Arthur Brock and Eric Harris-Braun's Holographic chain distributed application framework, together with 2) Mikorizal.org's Holo-REA economic framework - an Open Value Network (OVN) based on the Resource Event Agent (REA) accounting model (first developed by Bob and Lynn and Tiberius), which works as a transparent alternative to black-boxed corporate Enterprise Resource Software (ERP). OVN's can be used to fund open source hardware projects, and help with the transition to Commons-based peer production.
But I just think someone needs to point out the hypocritical and 'privacy-washing' behavior of corporations who 'open source' non-critical pieces of code and then leech on free software developers and destroy and corrupt these people's hacker+maker philosophy with wads of cash and a life of consumerist 'luxury'.
All of these actions are in turn based on the Silicon Valley lone Genius Myth, which bears the unspoken underlying promise of individual greatness and merits [2]. Damn it is painful to think back to how much self-loathing this delusional belief brought onto myself.
[1] https://www.opendemocracy.net/en/oureconomy/plunder-commons-...
[2] https://www.technologyreview.com/2015/08/04/166593/techs-end...
I've been very fortunate that my open source project was able to get a lot of attention early on (5 years ago) and has been able to get a lot of steady traffic from word-of-mouth since. I don't know how anyone could independently launch a successful OSS project these days.
* does a horrific job with documentation
* delivers millions of packages with demo-grade half-finished projects
* has tutorials which show basic functionality, without going into any sort of depth, which people glue together by pattern-matching
That doesn't work well in general, but for something as complex, deep, and, well, architected as React, it doesn't work at all. People really do need to understand reactive programming, functional programming, and deep concepts to handle React well. Resources to do that don't exist.
This is the claim for React's documnetation:
"The React documentation assumes some familiarity with programming in the JavaScript language. You don’t have to be an expert, but it’s harder to learn both React and JavaScript at the same time.
We recommend going through this JavaScript overview to check your knowledge level. It will take you between 30 minutes and an hour but you will feel more confident learning React." source: https://reactjs.org/docs/getting-started.html
Really? Read that again. REALLY? Someone with 30-60 minutes JavaScript programming is expected to code in React?
That's the target audience of most of the docs, and nothing goes far enough to get people qualified to use the tools. It becomes a magical black box. The posts in this thread show this attitude too: "You don’t really need to understand how React works, you just need it to work"
"to CHECK your knowledge level"
Doesn't sound at all to me like they're saying "read this and you'll be ready to learn React". More like "if you find any part of this overview to be confusing, you might find React confusing."
Also, I learned enough React to be dangerous when I didn't know anything about reactive or functional programming. I imagine plenty of people have had the same experience.
"Handling React well" is subjective. What are you building?
> but for something as complex, deep, and, well, architected as React
I'm not sure what "architected" means in this context. But re: complex and deep -
React is complex to the extent that you need to build complex things. It is deep to the extent the developer requires. This is a great aspect of its composable design - it's just components made of components made of...etc.
But people don't learn React by building huge, complex, deep things. They build simple things, and go from there. In this respect, React does a great job with documentation. They start small.
I'm a huge fan of React, but without understanding of why it is, people use it wrong all the time.
I also have additional links on both React's internals [4] and React hooks specifically [5] that should be useful.
[0] https://pomb.us/build-your-own-react/
[1] https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-...
[2] https://overreacted.io/a-complete-guide-to-useeffect/
[3] https://www.swyx.io/speaking/react-hooks/
[4] https://github.com/markerikson/react-redux-links/blob/master...
[5] https://github.com/markerikson/react-redux-links/blob/master...
I guess the single boon to the lock-in theory is that JS devs will happily spend time rewriting code to the latest, hottest framework.
For a long, long time, I thought that to provide the values that React brings, the UI framework being a black box is inevitable. Almost all React-esque libraries including but not limited to React, Preact, Mithril felt like a very thick abstraction over the DOM APIs.
But then I saw Crank.js[0], and that felt very intuitive and a thin abstraction, while retaining the good parts of React-esque libraries. I don't really know why it feels like that - I'm guessing it's because it uses native JS features that you already have a good understanding instead of some magic that happens in the React runtime.
I'm very looking forward to it, and I would like to urge everyone to try out Crank.js if you feel that React is now not intuitive enough.
[0] https://crank.js.org
"This system is hard to work with" -> {Abstraction created} -> {Abstracted extended to support new features} -> GOTO 10
Now you have n+1 systems to learn & reason through.
[1] https://xkcd.com/927/
Isn't that exactly the point that the big image on the front page is making? If most people have a mental model of a technology that doesn't match what the company is putting out, it makes very little sense to blame the people who have the 'incorrect' mental model. If it wasn't so widespread, your point would be much stronger. But the fact that the core pieces of react are misunderstood, especially when React publishes documents explaining how all of this is supposed to work and how you're supposed to think about this is an indication that something is wrong with React, not the people who use it.
While you're right that we shouldn't "blame the people", I think blaming the company / library in this case doesn't fly either, given the specifics.
The "incorrect mental model" people have about React is based on two things:
1. the prevalence of OO concepts in programming education and in practice in most engineering teams
2. the introduction of class abstractions onto JS prototypes by the ES spec.
followed by:
3. React bundling things like `createReactClass` and encouraging class abstractions in their docs in the pre-hooks days
While the 3rd point above may have been a mistake on the part of the React team, I do think points 1 & 2 are much bigger factors here.
> something is wrong with React
The only thing "wrong" with modern React is that they're challenging the status quo in popular programming concepts with something they believe is a conceptual improvement.
You can disagree with them on whether it represents a true improvement, but saying they're "wrong" because their conceptual model is a departure from the status quo is pretty reductive.
What makes this point tricky is that React did initially introduce their library with OO concepts for years.
To put that in context: that was at the time ES was starting to introduce OO abstractions to the spec. and it was somewhat trendy to go in that direction. I never got the impression that the React guys were heavily invested in that paradigm, and they definitely moved away from it very quickly after first encouraging it in their API. Everyone makes mistakes.
As a side-note: I think class abstractions in ES are a feature that in retrospect is less of a great idea now than it may have seemed at the time. ES class abstractions obscure their own subtle issues (in a very similar way to the article's fake Twitter screenshot jokes about React hooks).
- From 2008-2014, _everyone_ was writing their own "class-like" abstractions (see: Backbone, Class.js, five million other "inheritance" libs). So, the React team wrote `createClass` as their own implementation.
- When ES6 classes came out, the React team took that as an opportunity to drop maintaining their own abstraction and switch to something that was actually standardized, and reduce the amount of magic behavior (auto-binding, mixins, etc).
- Function components came out in React 0.14, and were initially limited to just rendering based on props - no state or effects possible
- Hooks now give function components the ability to have state and effects. In addition, encouraging a move away from classes dovetails into the React team's long-term plans for the React APIs.
The class abstractions added to ES spec. didn't happen in a vacuum; it was very much on the back of community demand. Backbone especially had an outsized influence.
Perhaps that was a necessary step toward realising tools to solve problems without those abstractions, I don't know.
Whatever the case, just because we wish solutions to those problems were easier to understand doesn't mean reality owes us that. I suspect React in particular, being in the web dev space, has a lot of people working with it who have very little CS background. Because they don't understand how React works under the hood or even above the hood is "something wrong with React"? I'm not sure I buy it.
I've seen a lot of really poor React code that breaks all kinds of best practices, many of them explicitly laid out in the docs. Even before hooks came along. In fact it's been hard to find examples of people who understand the dom well, much less React. I will continue to suspect there's something wrong with most of the people using React, not React itself, which from my perspective has only become better over time.
Another issue is even with people with a CS or another STEM background, they only get taught in the "traditional" OOP sphere on top of blocking thread environments. Those usually have a hard time wrapping their heads around higher order functions or async-based development (and to be fair, I also had a hard time when I first encountered it).
To my mind they are oftentimes magic pixie dust that can turn a hideous, verbose and inflexible API into something humane and readable.
If you bring up a scenario, I can probably poke holes in it. Done it many times in many debates. I don't mean to sound arrogant, but I keep winning THIS one for whatever reason.
I don't disagree, but my follow-up question with that statement is "ok, now what?"
If you've got a weak/inexperienced developer who's stuck in a framework where they have have to start grokking async/HOF/whatever to solve the problem they've encountered, where do they go from there? It's fine and good to blame the framework they're operating in to be shitty, but they a) didn't have the skills initially to make a solid decision about the framework to use, and b) are now likely stuck with it (unless they're going to do a rewrite with something else).
Early cars were hard to learn, drive, and maintain. Over time they got better via trial and error by manufacturers. The desktop IDE's of the early 90's were like this, but got better over time (until web ruined their market). However, the web is still stuck in 1903: simple things are esoteric. Perhaps because too many other things about "cars" keep changing? Something is wrong. CRUD web dev is a mess.
https://github.com/dai-shi/will-this-react-global-state-work...
with concurrent mode i think of what could be, web applications that can compete against native for the first time. as well as making making components that are resilient to async issues / making async a high level concept. there's a little churn for sure (for library devs, and a specific subset), but imo completely worth it.
Native apps feel better than web apps because they have robust UI libraries that web apps do not. React concurrent mode will have zero effect on that.
If the argument is "React concurrent mode will make web apps faster so that they feel more native", my response would be to use something like Svelte, which is available today and is considerably faster than React. React is slow.
Concurrent mode may make React faster but it'll just be making up for React's past mistakes, not the web's.
What's your definition of component?
With what React is attempting currently your app will render as much as it possibly can while maintaining stable 60fps, the rest gets deferred while it can differ between lesser and higher-priority updates. If you doubt how important scheduling is, look at practically any feasible list component, they're all virtualized. With React every aspect and corner of the application is like that. In theory it could outperform native apps.
Btw, there are countless of robust desktop apps being made with HTML: VSC, Whatsapp, Skype, Spotify, Notion, Hyper, Discord, Slack, ... thought most of them will still feel sluggish compared to a native counterpart. React will change that.
VSC: chokes on files larger than several mb Slack: eats all of your memory, often hangs and just whites-out while I figure out what to do. Skype: has this app ever actually been good? Spotify: not sure I'd call it robust, but it's functional...enough.
> In theory it could outperform native apps....thought most of them will still feel sluggish compared to a native counterpart. React will change that.
My understanding is that native apps hook into far lower-level functionality and run with _signficantly_ less overhead. They simply execute faster, and far more directly. I don't see how React and needing to go through react-framework -> JS -> V8 -> etc would possibly compete with that, let alone outstrip them.
The problem is essentially the same. Native apps are also conflicted with load, they have better means than we have on the web to deal with it, but it's still low-level and complex to orchestrate, threading for instance. Any one of those means pushes your app into async issuee, race conditions that you need to reconcile. With concurrent mode scheduling is a first class concept, your components won't be subject to race conditions. React maintains 60fps, high-priority content (user input, animations, transitions) can be ran fluidly while lesser priority content gets deferred. It has a good chance of outperforming multithreaded native apps with that model.
This demo illustrates the issue: https://youtu.be/nLF0n9SACd4?t=172 which is universal. You run into this on native platforms as well as on the web.
Isn't the likely way forward to move the computationally heavy parts of the app over to web workers and to keep the main thread almost exclusively for UI work?
Lit-html, which is using template literals, is another good option.
[0] - https://staltz.com/some-problems-with-react-redux.html
https://github.com/flutter/flutter/issues/11609
https://github.com/flutter/flutter/issues/15922
It's probably because I've been reading and writing HTML for +20 years though.
hyperscript is about as close to a middle ground as we can get. It's compatible with JSX for the folks that really really want to see angled brackets, while still being uniform javascript like other API variations (div(), html`<div></div>`, etc). The lit-html syntax is not bad either, but template strings did not have as widespread support back when mithril originally came out.
Since the framework isn't interested in chasing trends and since it provides extension points via lifecycle methods, there's really nothing novel that needs to come from the framework itself.
I know some of the more popular frameworks make it seem that webdev is constantly in churn/evolving, but if you look at React for example, other than the hooks paradigm shift etc, it hasn't really changed all that much in scope over the years either (the same can be said about other libraries as well).
For example, Mithril could easily be used w/ coffeescript when that was still a thing, and people use it with typescript these days too without much fuss since TS is also a project that decouples well. And this is with zero changes to the framework. You can integrate dragula or plupload or google maps or whatever via lifecycle methods as you always could too.
So, TL;DR: I think the focus still remains on making it as stable and robust as possible
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/87f2...
[0] https://github.com/reagent-project/reagent#examples
I literally can't write more than 100 lines of clojure without accidentally shadowing a function binding with a variable binding. I think the only way to break the habit would be to abstain from common lisp for 6 months or longer.
In practice I haven't missed the flexibility of a lisp-2, if anything it's just made my code more readable because my names are forced to be more descriptive
Can you elaborate on this? On first glance it seems the same, just with a syntax that uses different symbols than HTML?
That comes with some very real downsides - mostly getting jsx to work requires a bunch of extra (ugly) tooling. On the other hand, very complex components look very clean.
Hyperscript when you have a relatively nested dom element gets quite messy and hard to visually parse for me.
Mithril was sufficiently thin for me to drop into the debugger, say "oh, that's how it works" and fix.
I'll take a look at crank though. I do frontend dev only to make my hobby projects accessible to friends and family, so the less to remember, the better.
https://meiosis.js.org/
Just start with creating web components in Svelte, include them in existing React code, and slowly phase out slow, and old tech that React is. This is just frontend lib, why are people so religious about this. You still use Node, JS/TS, etc.
Im I troll? Don't know, but that is just what I did year ago. Now I just laugh when I see articles like this, buy I also feel sad for small entrepreneurs that have to pay big $ for code in "dated tech" - thinking "they are on the edge".
It's promising, especially for smaller projects/MVPs, but I still have no idea how well it will scale with app size/team size (and have yet to see good evidence that it does it well).
I just find it ironic that people dog on React for being the "default", but then also can't recommend Svelte fast enough, seemingly because its just "not React".
In our setup with parcel we didn't get good error messages and line numbers (it spit up internal compiler errors), but it might have to do with our setup. Trying it at home with snowpack it gave comprehensible error messages.
- jQuery - Backbone - Ember - React - ???
Skills I learned in college about writing SQL are still relevant today, several decades later. Skills I learned coding for iOS (even Swift!) years ago are still relevant today. CSS and HTML skills I learned decades ago are still relevant, etc etc. Python/ Django knowledge from 10 years ago is still largely relevant. React/ jQuery/ EmberJS/ Vue/ Angular/ Grunt/ Gulp/ Webpack/ Underscore/ CoffeeScript/ etc... damned near every Javascript library I've ever worked on has an extremely limited lifespan in terms of relevance. Even within React, it's hard to keep relevant. Class based React? We're doing Hooks now!
> why is that a bad thing?
It's only bad if you have to try and maintain 10 year old Javascript and in order to do it, you have to learn a whole new paradigm. IMO it's doubly bad right now since so many people are abandoning semantic HTML and more or less rolling everything as their own custom components.
My post was in response to a suggestion that the fix for all the React issues was in fact replacing React entirely.
Well said. Perhaps my deeper point is that hooks and soon Concurrent Mode force devs to come to terms with the fact that they _don't_ understand React internals (hence my usage of black box) and that their mental models were wrong this whole time (although some might argue still pretty productive).
I also think Crank is SUPER interesting on so many levels. I built a few demos with it and am fairly impressed. However, practically speaking (and I'm putting my developer relations hat on), I think its generator API is just too intimidating to junior developers.
That said it's still a mental shift. Sometimes I feel like I'm writing React and not writing JavaScript.
Is Concurrent Mode basically a way of addressing performance problems in React, or is this in some way a feature that adds something novel? Or is it just a side effect of an unwillingness to move away from functional programming?
I write React at work, but write Svelte or Vue at home, and I've always found React's abstractions to be the most hard to reason about, and from the looks of it CM will make this more challenging (??). Thanks.
For those that do, this isn't an issue, and for those that don't, this isn't an issue either. Their mental model may be flawed, but as long as the IO is the same, do they really care?
Concurrent mode isn't really a black box. Its just a shortcut to throw away work that would otherwise be invalidated.
The point of an abstraction is to create a "black box" of sorts around some primitive. I think all it boils down to with what the author is saying is that the React team is changing how things work under the abstraction, and therefore some assumptions people made about leaked semantics are no longer true.
Mithril rendering semantics have always been more or less this: on an event, redraw everything. React semantics started that way too, but now there are a whole lot of other semantics under the hood (for example, the rule of hooks provides some semantic guarantees that enable a hot reload implementation to be more robust). Concurrent mode is another example of semantics that benefit from rule of hooks guarantees.
I think when I see people complain about the rule of hooks is that there's a dissonance between the strict semantics of hooks and the expectations of what the semantics should be (for some definition of "should", usually related to ability to reason about stuff in some specific way)
I'd say that overlapping several different compatible underlying functional semantics under one umbrella of very strict API semantics is an interesting and somewhat novel approach to supporting some cool infrastructure (i.e. ability to do deep hot reloading stuff, animate in IoT devices in a renderer-agnostic way, React Native, granular reactivity via memo, and the list goes on). Where I think React missed the ball a bit is that the API semantics don't always feel ergonomic for the use case they're meant to serve (for example, I've seen a few occasions where nested hooks ended up w/ long code review threads debating obscure minutiae)
When I see people praise Svelte, I think the reason is similar: since it doesn't need to artificially create constraints to support every use case under the sun, its API semantics are able to align very closely to people's expectations.
[1] https://github.com/ryansolid/solid
Reading between the lines, this is a criticism of hooks if they're viewed as a wholesale replacement for classes; from experience I'd argue they're not—they're just a convenient tool for simplifying common patterns. I'd imagine the author knows that to be the case and instead of just using classes where appropriate (or where they wanted), they had to rationalize using hooks because of the aforementioned "but everybody else is using hooks" problem.
I suffered from this behavior for years before I realized it was impeding my work. The term that came to mind for the phenomenon was "The Invisible Developer:" a non-existent developer sitting over your shoulder always judging you for your programming choices. That developer doesn't exist. If instead how "in fashion" your code is is the standard on your team: you're on the wrong team.
Most of what you've described is just peer pressure. The only reason I know that is that I shared this exact opinion until I said "this is stupid" and started doing things my own way (to much success and peace).
Class lifecycles being replaced by hooks is a radical but much needed change. Learning it isn't complicated and it will enable you to venture on as everything around you sheds the class based component approach. Swiftui, Vue, Svelte and ofc React are just the beginning.
I disagree. If you know typescript, it's still quite a leap to be able to code with angular, and debug weird stuff where you stare at a blank page, and the back trace in the dev tools include not even a single line of code you wrote.
Also, the language isn't really enough. You need to be familiar with the tooling (npm/yarn, babel, whatever) to use most libraries; so unless you do everything from scratch, you have to deal at least with the churn of the toolchain.
It's great for online educators and others who monetize devs though..
The JS ecosystem almost seems like it's self promotional, where the monetization opportunities result in a higher self marketing activity of individuals on platforms like Twitter, which of course builds up hype and draws more people into it.
ES6 -- 2015
jQuery -- 2006
React -- 2013
React Native -- 2015
Redux -- 2015
VueJS -- 2013
6to5 (now Babel) -- 2015
Webpack -- 2012
ESLint -- 2013
jslint -- 2002
ExpressJS -- 2010
Lodash -- 2012
UnderscoreJS (basically the same API as Lodash) -- 2009
D3 -- 2011
Blockly -- 2012
Node Red -- 2013?? (I'm not sure when IBM first released the project)
Bootstrap -- 2011
PDF.js -- 2011
WinJS -- 2012
SocketIO -- 2012
ThreeJS -- 2010
dotenv -- 2015
momentJS -- 2011
node-sass -- 2012
Winston -- 2014
yargs -- 2011
Modernizr -- 2009
Jasmine -- 2010
Mocha -- 2011
Jest -- 2015
All of these are at least 5 year old and most are 8-9 years old. Look over the most downloaded npm packages and you'll find this to be generally true for all the top packages.
angular -- 2016
That's an example where, when you jumped on the bandwagon at the height of the hype, you were thrown into a backwards incompatible rewrite pretty quickly.
And while npm has been around for quite some time, my outsider impression is that was, for some time, basically discouraged from use, because yarn was so much better.
Compare that to Ruby on Rails -- 2004, Catalyst (Perl) -- 2005, Django (Python) 2003.
Time moves slower in enterprises, with upgrade cycles more on the scale of 3 to 10 years.
Yarn solved some npm issues they refused to tackle, but npm got motivated and has now solved most of them. Meanwhile, yarn 2's release has been a disaster and has seemingly resulted in most people (myself included) moving back to npm.
I've done Rails and Django work. Rails in particular took years to migrate to the next version. I'd add that Rails has seen 6 versions in 16 years which gives around 1 major breaking upgrade every 3 years (in truth, there's been about 1 major change per year as point releases are pretty big). Likewise, wikipedia gives almost 20 major django updates (I haven't used it in several years, but point updates used to have a very big risk of breaking the project I was working on).
Be that as it may, Angular 2 meant nobody was willing to commit to any fixed time span to support Angular.js, so it basically forced everybody to migrate off of Angular.js, introducing the toil and churn we were discussing.
In respect to swimming against the tide, this is where experience comes in and knowing both how and _why_ something works the way it does. Over time, you can develop your own opinions and not have to worry that much about what everyone else is up to.
Admittedly because I mostly work alone that's a privileged POV of sorts, but I think teams can "act as an individual" and adopt a similar attitude (scale of team permitting).
In the end, I'm sticking with Java and vanilla SDK because it just works and only changes ever so slightly with each major OS release. Also my apps run pretty darn fast on 7-year-old devices because they only use the CPU to do useful work.
Extensions. Basically every project has its own dialect of Kotlin that you have to know everything about if you're to understand anything. And good luck doing that without an IDE.
> It's possible that you have just worked in bad codebases abusing Kotlin sugar.
I've never actually worked with Kotlin, I've just seen many examples of it. The problem is, the language itself pushes the developer to use all the sugar, and they have to control that themselves. As opposed to Java, where writing unreadable code would take extra effort because of how dumb and simple the language itself is.
Also, to me it feels like an abstraction on top of Java that gets in my way as opposed to being helpful.
I love dumb programming languages.
https://github.com/flutter/flutter/issues/51752
At the very beginning, Virtual DOM manipulation/management was beyond me. Then they updated the engine to React Fiber. If I thought I understood anything under the hood, I really didn't then.
I believe the author is talking about tiny unexpected side effects as a result of the complexity. Like on a particular hook, 1+1=2 out to 7, 9's. But if you do it just in the right way, you'll get a weird side effect (i.e. 1.0+1=3).
This is a typical result of being a ultra power user and I feel the author's pain.
FWIW, I don't think being a black box is bad. Kernels are black boxes, CPUs are black boxes, to so many of us anyway.
The spirit of what the author is trying to make is - this black box isn't completely predictable. It's only mostly predictable - it needs to get better so everyone can rely on it.
I do not envy people struggling through the adoption curve of using Hooks. I don't know enough about them to know how to "fix" them, nor do I have the time to care about that problem - but I would love to see a different syntax, abstraction, or some kind of guard rails around them.
I might be wrong, but it has always felt like scope & hoisting are the primary language features that hooks operate on... both features that I prefer to avoid.
Adopting them seems to require the same leap of faith that is required with something far more complex like early angular versions. The "I don't get it but I'll just follow the rules" kind of vibe... But the web community seemed to understand and fall in love with Rx a few years ago, so I'm sure hooks can become more well understood, too.
The most telling thing about hooks to me is that I need a library just to use intersection observer, because the way you have to implement it to replication the same 5 lines of code from vanilla js is so much more complicated.
React is great, and groundbreaking, but with 20/20 hindsight, there are better ways.
[1] https://www.drupal.org/forum/general/general-discussion/2006...
Class components are easy to understand and reason about (mostly) - but they result in a lot of boilerplate code for simple functionality and event handling. Hooks, to me, are the opposite. They have all kinds of limitations and footguns which you need to be aware of (yes linters help) but they give the code a much cleaner appearance.
I personally prefer obvious boilerplate over clean aesthetics but I know lots of people who prefer hooks. I've sinced moved to Preact and have not missed real React once.
The most telling difference after starting to use hooks when working with both junior developers and more seasoned ones is that code that seemingly (and intuitively) behaves in one way actually does something slightly different, or worst case - something entirely different. Most often the culprit is a combination of the hooks themselves, the rules and the more general issue of the dependency array and lack of built-in immutability in the language.
This happened before hooks as well, but the class syntax and lifecycle methods felt like a thinner layer on top of JavaScript. Hooks is a much more proprietary concept that tries to solve a much wider problem - having stateful functions, except they make no sense outside the realm of react as they exist right now. Maybe some form of implementation using generators would bring it closer to the language, but that would most likely introduce it’s own set of challenges.
Don’t get me wrong - I enjoy working with hooks, but it just doesn’t feel quite right that they are so tied to some «magical» implementation that requires a large set of rules to behave as expected. It helps to look into the implementation, and especially to reimplement a simple version of react with hooks yourself - but that’s just not a realistic option for many.
Kudos to all the innovation coming from the React team and community though - I’m sure they think about this stuff all the time.
> they are so tied to some «magical» implementation that requires a large set of rules to behave as expected 100% agree here & with your sentiment about the Class API
What's cool with a monadic interface is that you can create lots of other interesting things, as long as you adhere to the interface. For instance, I think it's possible to achieve something similar to async render functions without specific support for it.
also, you shouldn't use useState unless you want it to rerender, which you don't because you're printing to console. use a ref instead for myNumber.
the problem you are trying to solve, updating a number if someone clicks on something, is already solved in React:
then you can simply trigger a click by calling .click() on the forwarded ref wherever you happen to mount it.That's what https://crank.js.org does. I haven't tried building a real app on it yet, but I have to say it does seem pretty elegant and promising at a first glance.
https://www.youtube.com/watch?v=1jWS7cCuUXw
I agree on 2 of the points of Jared Palmer but disagree on one:
- [agreed] The new "Concurrent Mode" will take things to a new order of complexity. I am actually very afraid of this, it seems like one of the things that might actually kill React, and I love working with React. I like it so much that I've invested into creating few React libraries to make my life easier.
- [agreed] React Hooks are difficult to get started with and to really understand them. IMHO this is mainly due to "React lifecycle", which is just a difficult concept (even with classes!). Life is not easy, and there are some times that there's complexity and you need to learn new complex concepts. No issue here IMHO.
- [disagree] React Hooks is currently magic. While it's a complex piece of software with many small details, once you understand fairly well the lifecycle (and React docs are great at this, and Dan Abramov's https://overreacted.io/ digs a lot deeper for the curious) all bugs are very clear.
I am currently mentoring someone in React who already knew HTML+CSS+JS, my recommendations are: get used to the syntax by practicing, learn the 3-4 typical libraries, and learn very well the lifecycle including how useState's setState and useEffect's dependencies work. That's most of day-to-day React work.
https://github.com/flutter/flutter/issues/51752
> Reusing a State logic across multiple StatefulWidget is very difficult, as soon as that logic relies on multiple life-cycles.
The logic should be inside StatefulWidget, and StatefulWidget reused - so no code duplication or hooking into the parent's lifecycle methods.
> A typical example would be the logic of creating a TextEditingController (but also AnimationController, implicit animations, and many more).
Looks to me more like TextEditingController should be turned into a stateful component so it can be reused in the render - this lets the framework handle its lifecycle and none of the boilerplate is necessary. I've done this a couple times with variations on AnimationController: It uses React.cloneElement on its children to pass down the appropriate state, and because it was itself a component that simply rendered its children, React handled all the lifecycle stuff within that component with no hooks to the parent.
Quick edit: This reply in that issue is very relevant: https://github.com/flutter/flutter/issues/51752#issuecomment...
I can here kinda see where it's coming from, but we've never had reason to use hooks like that, so I guess I just don't see it as as much an issue. Also, a very important part of it that some other comments over here seem to not be aware of:
> In practical terms, there are a few things here. First, it's worth noting Hooks aren't an "extra" API to React. They're the React API for writing Components at this point. I think I'd agree that as an extra feature they wouldn't be very compelling.
There are a lot more examples, it is worth going through the entire ~250 comments, even though it may take some time. I only understood after doing so, not necessarily by just reading the initial post.
We've been able to get rid of a lot of annoying and confusing stuff when working with class-based components (though perhaps not all of that was related to hooks but also due to early React boilerplate/tutorials which may have proposed things which are now considered bad practice even with class-based components). No more componentDidThis componentWillThat but a simple effect api (the cleanup function can be a bit confusing at times though). No more unclear setState calls but clear and logically separated state updates. No more class method callback binding hacks but simple functions. No more `this` confusion. No more "Pure" and shouldComponentUpdate confusion but a simple memo api. No more weird Redux 'connect' biolerplate but a simple select and dispatch function.
As far as our team is concerned, React has always been a black box and it has helped us a lot being productive. Perhaps it has become harder to reason about how React itself works, but it has definitely become easier to reason about the components built with it.
I understand that React is supposed to be an efficient and "ergonomic" way to develop for the increasingly complex array of devices out there in the world, but I have had too many poor experiences with React to consider it better than direct UI programming for my needs.
What V-DOM is trying to address is tracking what is changing in your application so that it can modify the DOM on your behalf, simplifying app development and reducing bugs, sort of like how a Garbage Collector manages memory for you and gives you similar benefits.
Look at Svelte, it doesn't have a V-DOM and it smokes any V-DOM framework in terms of performance.
*: ideally it would be minimal in a sense there is no smaller/faster representation, but thats of course not the case in real applications.
Svelte is essentially that. You write simple components. The compiler checks the dependency graph and converts your code into the vanilla code that would be needed to render those components and make the necessary changes when you modify a reactive variable.
That's why Svelte apps are much faster and smaller. You also write a fraction of the code compared to React/Vue/etc which I think it's actually the best part about Svelte.
Each component is just HTML/CSS/JS in a single file, sort of like Vue but cleaner.
If you're curious I recommend either the "rethinking reactivity" talk from the author: https://youtu.be/AdNJ3fydeao
or the tutorial: https://svelte.dev/tutorial/basics
Both are great!
A lot cleaner!
Sure! The fundamental problem that React solves is turning some canonical notion of state into the DOM (with an eye on composability). This is the central problem of web dev. Once your application grows large enough, you will inevitably end up re-implementing a much worse, ad-hoc solution out of $ or innerHTML. You will build your own React and will be responsible for maintaining it! If the scope of your app is small any solution OK.
I'm speaking from experience: I have built several Reacts over a decade or so - so before it existing and a few afterwards.