React is holding me hostage
emnudge.dev
emnudge.dev
People tend to compare these frameworks on things that don't matter - often it's performance. We used to compare React performance to AngularJs performance too, which was meaningless.
VDom is nice. Reactivity in signals is nice. Limiting rerenders is nice. But I choose frameworks because of developer ergonomics.
The killer feature for React was - 1. JSX - typing and auto-complete for components, colocation. 2. No direct dom access. (Good bye $element)
Most frameworks outside react still use templates. Even when they support JSX like syntax (aka vue 2.0) the default are templates. Templates are a no go for me. I use them for blogs or static websites, but applications are easier to make and maintain with actual javascript.
Luckily none of the other frameworks, even Angular, have rampant direct dom access anymore.
Hooks aren't a problem in general. It's just the useEffect hook. Unfortunately that's a big problem. That hook should never have existed. And it was clear from the start it'll be a pain from the limitations around it. It requires a mental model detached from everything people are used to and from other things around it.
When using React I usually just use MobX and everything just works.
React is very sluggish when updating many elements at once, for not very large values of "many". With some regularity, I've debugged React+MobX jank issues where a bigger update, such as switching from one panel to another, takes upwards of 200ms on a mid- or low-range machine.
None of this is perceptible on our beefy dev boxes, which is why I think people disregard it, and why the modern webapp experience is so miserable for the average person.
I see this claim a lot and I'm curious what this is based on, can somebody drop some links to further reading?
I'm averaging a 15-30 second TTI on the most js-heavy sites.
N.B. No one is using the app from their mobiles. iPad and computers only.
Our reasons for choosing React when there are so many alternatives: prior knowledge, ergonomics, easy onboarding, ecosystem.
Actually, why aren’t web-components a thing, that’s another story. But componentization is why React creates clean code.
The reasoning I get all the time is "Why would you want to do that? That's stupid".
It's just so much nicer honestly. I'm not a react fan at all but that's one thing I miss about it.
Honestly, if anything I find react's modularity story much weaker than the competition. In react there's no page-wide state and the story around styling components with CSS is a huge mess.
In comparison, Svelte components feel much more modular & self contained because the styles are embedded with the component in a standard way.
90% of the users use shitty hardware. Everything is sorta sluggish on their computers - they boot up slowly, the bunch of crapware in autorun take their sweet time to load & phone home, their wifi us overburdened with devices. Most of the software experience is sluggish for them. They don't care if their web app is sluggish too.
Anecdotally, those 90% of users are not happy about their experience, they just tolerate it.
If you are forced to use an app with bad performance (say Teams) you cope. Humans are great at coping. Maybe you turn it off and back on again periodically, or alt tab to something else while it's showing a spinner.
It's true performance isn't a major selling point but IMO that's because most software products are not sold to users. They are packaged with other products, part of monopolies and imposed to users by others.
I buy video games where performance undoubtedly matters. Apart from that, most software I use, I didn't choose, and I'm pleasantly happy when it's not garbage (Outlook, IDEA) and annoyed when it is (Teams, Facebook). In either case, performance wasn't a contributor to my choice: I didn't have a choice.
All the sluggish steps led them to the usage of the web app they need to use, and they need it to be fast. At least, faster than rest of the crap so far. Heck, they may spend rest of the day with this app..
$250 in an Android phone can get you a SD 695 5g these days. IT's not fast per say but it absolutely doesn't suck.
Most users have no idea how to remove any of it. Or, worse, they'll enable all of the preinstalled antivirus programs because they want their computer to be safe. And it gets worse. I visited my parents once and noticed something weird on my dad's macbook air. Turned out he'd gone out and bought Norton antivirus to install on it (!?). Norton installed a chrome extension which replaced the banner ads on every website he visited with their own ads. I manually deleted the extension from chrome, but norton put it right back again after chrome restarted.
If you don't believe me, use performance counters and measure it. Your website runs way slower on your users' computer than you think it does.
But the point I was making was that the average computer has actually gotten pretty good. Most users use near-latest chrome, most laptops have gotten much quicker.
And that’s before noting that the average cell phone in the US has BETTER js performance than the average computer. Most US mobile users have a modern iPhone that is faster in single core performance than some 10th gen laptops.
We still get <100ms page delivery with server side rendering and lightweight JavaScript DOM overlays. Our React infested competitors, not so much to the point their clients have been shitposting on twitter about it.
And we actually can debug our product!
React is like nearly any other tool, use it well, and it's great. Well optimized React is lightweight to the client and a joy to test and debug. That said, Web Components are even better, but I'm guessing that's science fiction to you.
Most React applications do not end up like that in the real world. They turn into poorly architected over complicated nightmares, particularly on sprawling apps which is the reality in the corporate space. Not everyone is building hyper-focused single function tools which can be crammed in an SPA type framework. And the users suffer for this.
One of the finest turds I've seen recently is my electricity company's meter reading facility which is an over-engineered react interface for a single web form with two fields and a confirmation box. The whole thing pulls 590k down to do that and takes 5 seconds for the initial page load on an M1 MacBook Pro. That's the real end game for most people. The only reason it's like that is because the people who built it don't know how to do it any other way.
And lets be honest about Microsoft: they do everything from a front end or user interface perspective and randomly discontinue bad ideas about 5 years down the line. Like Silverlight, most of WPF, bits of ATL and MFC, an entire mobile phone platform that got rewritten. And their competing framework WinUI 3 doesn't even work properly. Their own O365 web platform is a fine example of where this turns into a buggy mess. I bet react is dead to them within 2 years on one of their schizophrenic switcharoos. The only reason they're into it now is to capture some market from Electron.
1) MSFT has already used React for far longer than 2 years.
2) They have basically never used the technologies you mentioned (WPF, Silverlight, WinUI). They offer them as UI toolkits that run in their Windows environment and that’s it. Their failure to market and support these technologies is independent of what they do for their own development strategy.
3) They bought GitHub and effectively own electron now. Many of their biggest apps are on electron (Teams, VS Code, Azure Data Studio).
2. Yes they have. Half their developer tools were rewritten in WPF, they offered huge stacks including CRM on top of Silverlight and a huge chunk of windows 11 front end is WinUI.
3. Teams fucking sucks. VS Code is heading in the same direction. I've never used Azure Data Studio.
Huh? Those are Microsoft's biggest apps? Not, MS Word, the NT Kernel or ... windows 11? The XBox operating system project? Outlook express? Visual Studio? ... Github?
I'll grant that Electron is used by a few teams at microsoft. But I'd be surprised if even 1% of microsoft's engineers worked on products built with electron.
I don't love Microsoft, but it's for the best they adopt a well known and rounded framework like React, rather than try to invent yet another of their own frameworks, like the ones you mentioned. I don't know why this has anything to do with Electron, since their React push is for their front end frameworks for their main corporate product, Office365 (or whatever it's called today).
Both are not exactly light tho
I don’t have any numbers, just some anecdotal experience like the above.
It is not just speed. The UI of many sites suck too. Amazon, GoDaddy, for example.
Then there are ads. We don’t see ads in between content anymore. It is content within ads these days.
I am thankful that we can do so much online these days. But the experience could be better
But JIRA main performance issues in my experience are caused by badly sized servers for the level of use.
Jira is a 20 years old piece of software. I'm sure today's engineers do their best with the constraints they have. And I'm sure the 2002 engineers did their best with this period's assumptions and solutions.
I hate Jira as a product, but please don't attack people like that, have you never had to work on a product you're not 100% satisfied with? :/
I stand by what I said.
>I’m sure todays engineers do their best with the constraints they have.
There are two real constraints in the software engineering world: time and money (especially when we’re talking about an issue tracker, a wiki and a repo + CI\CD pipeline).
That Jira and confluences performance remains … not very good, suggests that the engineers are unwilling to, or unable to advocate for, spending the time and money to address this.
I find performance suffers mostly when media assets, advertisments, marketing and tracking scripts etc. come into play. The frontend rendering rarely makes a dent at that point.
But in most cases, front-end technology isn't the limiting factor.
No really. It is a B2B company that sells an idea to large orgs. "Know what is happening for everything and where you will be in a month.
It is not "Enable your workers to work more efficiently".
Jira simply doesn't really care about the average dev or such. In fact, most orgs use such a wildly configured version that it is pretty absurd.
Let me give you an example: Most companies have a workflow: To Do > In Progress > Testing > Done.
Foundationally, Testing and In Progress are tasks done by different operators. Jira doesn't, out of the box, conceptualize who tested a ticket and who developed it. It is all one field. You don't have seperate pointing for testing and development so you can't track QA capacity (Which is helpful to a team but not to overall planning as it just causes rushed QA). You don't have historical views of prior sprints "What was that Ticket I worked on last sprint?" (because that means nothing for forward velocity other than the final number) I could go on..but it all leads back to an absurd UI focused purely on projects and velocity above helpfulness. (And don't get me started on Jira's absurd take on SCRUM) Honestly, I'm kinda shocked no major software company has not just built their own and knocked Atlassian out of the park. I'm sure tracking velocity of other companies would be highly...helpful for Google/MS.
It's more or less one of those enterprise software packages that will be depended upon in larger orgs, because "nobody ever got fired for choosing $VENDOR". That sort of software tries to do a bit of everything, provide lots of features and customizability, sometimes at the expense of being more complex, bloated and slow.
Most people working on their own projects, when fully in control of the decision of what software they want to pick to best suit their own direct needs, might settle on something like Trello or even Kanboard instead. Personally, I self-host OpenProject because its features are a nice fit for my needs, even if it's still a bit sluggish (Rails app, limited hardware resources). Honestly, the performance of Kanboard was blazing fast when compared to anything out there - which is in no small part thanks to how focused and minimalist it is, which in some cases will be exactly what you'll want.
As another good example, I'd also put something like the Oracle database in same category: there will be many projects out there developed around it, as well as lots of knowledge, training, as well as entire professions built around it. But most people won't necessarily reach for something like Oracle XE for their own personal projects, they'll instead pick something like PostgreSQL or MySQL/MariaDB, because both of those are a little bit simpler to get started with and keep running, while still provide sufficient functionality.
This is an anecdote, but recently I launched all of the mentioned database options one after another in containers, for some testing. Oracle took around 10-20 minutes to start up an de usable. MySQL took about 5-10 minutes to become available for connections. PostgreSQL needed just 2 minutes. That's even before I get into how much data Oracle created in a container volume meant for data persistence (an order of magnitude more than MySQL or PostgreSQL).
I experienced similar behavior when setting up my own trial/testing license of Jira because I needed to do some integration dev work - with the resources given to it, I found it to be pretty sluggish and creating new issues took multiple seconds, which does get annoying when you also want to edit some of the fields, or have to do it often as a part of your work. Though I don't have exact numbers for that, I'm afraid.
Then i noticed a stark differences in attitude in the 2 studies I did at uni. One was more plain compsci. The other more web/mobile design and development. The later paid absolutely 0 attention to optimisation. Whether it was speed, download size or anything of the sort. The former treated an inneficient slution as invalid or at least graded lower. (Note this was in Beligum)
First time I started paying more attention to this where it wasn't when it wasn't in the context of being a budget constraint student was when I did a temporary IT support stint at a gigantic international pharma company and the software was so sluggish it was....insane. Dozens of people at our facility staring at a slugish webinterface waiting at every action and doing loads of those for every ticket. It was so infuriating I tried to make a browser plugin to prefill stuff with comon defaults the moment they were available knowing I'd never use it beyond those 3 months. Years of time must've been wasted staring at little loading circles because management did not use the software.
Then when I made native software for a manufacturing industry niche where i was told some suggested db retrieval and prerendering optimisations and such weren't worth the time....And sure. These were lowwage foreign workers using it, it didn't hamper much at all and our time was expensive. Maybe the business wouldn't get the money out of it....but then i ventured to production and notice more than a hundred people pulling the same actions many times a day thousands of times a year ....and see them waiting split seconds or multiple seconds depending on the actions that counted up to combined wasted minutes, hours, days, weeks and I realised what a load of bollocks it was.
Additionally when I helped extend various ERP's I realised the old ones were faaar from great but the move to web based interfaces really didn't do us much favours.
Then I come home and try to help my various layman family members on their comparatively slower windows and android devices and it becomes veeery apparent that this is not just a professional software issue. Slugish UI libraries on slugish frameworks on a slugish OS with various other slugish apps.
Coming home to a fast pc running Linux and using stuff i write in my free time using C++ or rust or even just various native apps on windows feels like such a extremely stark contrast.
My conclusion is that users won't care enough up to a certain point as studies show However I do believe that what those studies don't show is that for a good part this is because it's the default for many of them. They think this is just what tech is and all those countless small waittimes behind actions is normal.
Nngroup used to publish analyses of the state of usability, but I don’t think they have done one recently.
The old ones always showed progress, and that’s also what I would expect talking about the average situation.
Average progress doesn’t mean there are no shitty situations and we should always strive to improve, I just think claims like this are not helpful as they are used to make blanket statements about nuanced situations.
Unless you can back them up of course, and I would still love to see the data if anyone can find it.
I think it almost always comes down to one thing: Can people achieve the thing they want to achieve in a somewhat efficient way?
If the answer is yes there is lots of tolerance for all sorts of crap before people experience it in a negative way.
That means managing the experience. As example a multi minute upload process can be totally fine if handled properly, a .5s delay on an input can make it unusable. My point being; reality is a lot more nuanced than the blanket "it all sucks, and performance is everything" statement, and personally I don't think it's helpful. Unless we can actually look at metrics and assess their importance and how we can address them.
Don't get me wrong; we should absolutely keep trying to improve, especially crafting well made usable interfaces that are a delight to use. Performance is certainly very important, but it's not the be all end all of user experience and atm wrongly used to justify silly points why [my fav framework] is so much better than React.
The day they disable it, I’m not using it anymore.
1. Performance is very very rarely a contributor to a product success. Users prefer more features over more performant app all the time (both directly when asked and indirectly by what products they choose).
2. Rendering/client computation speed is rarely a contributor to real and perceived performance. It's almost always the async calls - how many you have, and how long they take. It's almost always a waste of effort to try and make your framework render at half the time when 99% of your lag is a database call.
3. Framework performance is rarely a contributor to the speed of your rendering. It's most often a problem with how you structured your app. You can structure your app poorly in any framework. (I would hazard a guess that in your panel switch example a differently structured React+MobX solution would not have the problem you described)
4. There are only very few scenarios where the rendering speed between frameworks makes a perceptible difference (usually when talking about large tables or similar scenarios), in all other cases it's a difference of a few milliseconds.
2. True, it depends on the type of app. For anything that is a type of "editor" - website builder, word processor-like thing, kanban board - you operate on a data model that you save in the background. Async calls are fairly unimportant for the overall feel there.
3. To me it's hard to untangle. The reigning paradigm is declarative UI, for great reason. It's so much saner than any manual updates. But this encourages a design where you don't think about what DOM updates will really happen after an action, and this is where the problem lies. A big part of it is also the DOM model and layout. In the extreme, you have a declarative UI library like ImGui which doesn't have any VDOM, it just rerenders every frame, and it's insane how quick it does it. I haven't been able to bring it to its knees, it just maintains 60FPS constantly, with a lot of frame time to spare.
4. It's not hard for me to believe this. I didn't say other frameworks are better. Could be that the whole DOM diff approach is the culprit, or the slowness of DOM updates and relayouts.
Most of my successful work has been specifically outperforming the competition in a way that makes users choose our product. Performance is an orthogonal feature that improves all other features, and even changes what your clients can do with your system, as in making new workflows viable.
> A 2017 Akamai study shows that every 100-millisecond delay in website load time can hurt conversion rates by 7%
> 10 years ago, Amazon found that every 100ms of latency cost them 1% in sales
Also misleading to imply a linear relationship. There will be a marginal cost, but no reason to assume constant.
You're not amazon
That said, having a performant website is nice, both for developer experience and for users.
I have to say I pick solid because it's so damn fast (okok, and because it has an API which is React-like but without the crap doesn't make sense or an extra custom runtime just because)
I close sites all the time when they fail to work quickly. I have aborted orders on sites midway through when the interaction became sluggish enough that I wasn't confident in the value of the product anymore.
This statement reminds me of those Gordon Ramsay shows where a restaurant owner says "the customers like my food!" when it's obviously subpar. The fact is that the customers that didn't like the food politely go away and don't come back.
Your other points get more directly at framework performance versus other performance concerns. I have fewer opinions about those.
Products almost never compete on performance, and the biggest, most popular ones are almost always the slower ones.
Regardless of your anecdotal evidence, there is a reason why this sentiment is prevalent in the industry - because PMs and devs who thought otherwise were quickly outcompeted by those that moved faster and released more features.
Both Google and Amazon have researched this topic and the results are readily available. First link I found: https://www.thinkwithgoogle.com/marketing-strategies/app-and...
Why do you think there some much time and effort going into improving performance of computing in general. Facebook Lite, android go, GPU's, cpu improvements, 5g, etc.
The important caveat is that once it's fast enough the gains are marginal.
But if you are still at the stage in product development where adding features will increase your addressable market by tens or hundreds of percents (which doing things like ‘supporting multiple European languages’ or ‘adding google login’ can do) then those performance gains are not where engineering investment needs to go.
I use Vim and I use VSCode. There is little debate about which has better performance and which has more features. It's also easy to see which has more users.
Based off how slow every SaaS service is in the B2B space, performance isn't important in all scenarios.
Site performance is much more API based, and that’s the same regardless of frontend. React has more library solutions to optimize the UX though, as it’s the most mature and popular.
Exactly. And those API calls are going out over the network. The caller has to serialize the request into text, the API implementation has to deserialize the text into values that can be passed to a local implementation function and then the API implementation has to take the result and serialize it into the return. Finally the caller has to process the result.
That's the simple case. Things get even more involved when you start using HTTPS to secure the data in transit on the channel and using OAuth to secure the access to the API. What appears to be a simple API call turns into a lot of back-and-forths with multiple servers - with all the network latency that entails. Then developers complain their website is slow. Gee, I wonder why!
And this isn’t just about 100 ms here or there. The frequency with which clicking a button takes seconds to have any observable effect is quite high. Coupled with modern UI trends where interactive elements aren’t clearly distinguished, sometimes users can’t tell a laggy button from a not-a-button.
I suspect a massive UX study bias here. Are people looking at telemetry to try to see whether users who completed some flow are happy? Those users (a) completed the flow, so they didn’t give up and (b) are likely enriched in those users who would use your site no matter what. The marginal users of poorly-functioning websites aren’t in the data set!
You might as well say, having users is very very rarely a contributor to a product success. We're over two+ decades into the 21st Century and we're still pushing a 20th Century mindset?
Why Lord? Why?
These two things are not even remotely the same thing.
Having users is a path to monetisation but having a high performant app no one uses is not.
In fact, if you have users despite performance, it suggests you have a home run product that can be optimised for performance.
Again, you can’t optimise your way to user growth.
These two things are also not the same. You start with "having users" and assume they're willing to pay and will stick around. You compare that to "having a high performance app no one uses" - explicitly limiting the scenario with an unrelated caveat that no one uses it.
A better comparison would look only at having users vs. a high performance app, which has too little information, or having users that aren't willing to pay vs. a high performance app that no one uses, which leave you in the same boat.
I said explicitly “path to monetisation” not “assume they’ll pay and stick around”.
I hope you’ll agree that it’s easier to find a subset of users that will pay when your superset of all users is large vs a super(?)set of zero.
Do users explicitly care about how many milliseconds somethings takes? No definitely not
Do they care if the application feels slow ? Yes absolutely
Do faster experiences subconsciously feel better ? Yes
Does that subconscious feeling, impact metrics like sales or conversion ? Yes it does
So people do explicitly justify usage decisions with performance, all the time. Agreed that overall features win out but it's often the case that multiple products end up with broadly comparable sets of features and struggle to gain a persistent advantage there. Once you reach that point, perf can be a competitive advantage.
Yet this is what all the JS people were saying in 2014 - 2015 when everything started to become SPA. They argued this is what the users want. That's been used to justify all this stuff for a very long time if you're on Twitter. When it gets traction within Twitter it leaks into orgs. It's the same argument that's used now for all the SSG,SSR,hydration,edge and whatever other buzzword.
The internet is miserable because of all these React sites. I know first hand because my wife has a Chromebook. Yet developers won't listen because they think 6x cpu slow down is good enough to test with on their $4000 Mac book pro.
If users really don't care that much about performance then why aren't we just rendering html and sending new html on every interaction. That's much easier to do, performs pretty well from a CPU/Memory standpoint.
We've taken on a lot of complexity over the years in defense of the users. The argument I go back to is what is "good enough" and the developers/product/design I've worked with don't know what this word means.
I
Server rendering can carry less of a payload to the FE but you aren't sending unnecessary data.
This is absolutely true!
I would say that some frameworks make it easier to make mistakes. For example, Angular can be highly performant...but the automatic change detection kills performance. But wait, you can fix that! Just make your components use OnPush Change detection! ...which is not...the default? Why? In any Corporate app that displays complex UIs you absolutely need to be using it everywhere. but yet.
Personally, I think it is to make it easier for beginners who don't understand why their observables are not showing content on the page but it is still annoying to set it in every component or hunt it down. This is a small part of why we turned to using nx and generators with configurations that add it by default.
https://infrequently.org/2023/02/the-market-for-lemons/#shri...
We have a React+Redux search page where clicking checkboxes takes about that long to update the checkbox, on our good developer machines.
I won't rule out we did something wrong (this page was pretty early in our React understanding), but we've also not managed to fix it due to how much is on that page.
It was all redux’s magic and simplicity was making almost the entire thing rerender on every keystroke. Of course it was the developers fault, but it’s so easy to end in that situation that I blame the tools because to me when you shoot yourself in the foot that many times you start to ask yourself if what you have is a footgun.
Hyperbole. Web apps would not be so ubiquitous and popular for solving business problems if your claim was true.
But yeah, I guess you're not waiting in line at the bank anymore.
However almost certainly ubuitity is one measure or factor in an item's usefulness. I'd also claim Usefulness inversely correlates with miserableness in the mind, but perhaps not in practice :P depending on how boring or miserable useful things are.
In general, I think usefulness overrides miserableness simply because the willingness to do useful things, despite miserableness, is clearly tolerated and performed all across human economies and societies through time. all just depends on definitions
Performance people get offended when they hear things like that. I imagine what they will tell a person who says something like this is to:
- Look at the traces. Real metrics, on real devices that users have, not the one that developer has.
- Consider either large contentful paint (will likely be subpar with client-side rendering) or first input delay (will likely be subpar with server-side rendering). Consider, too, the new interaction-to-next-paint metric (rumoured to be bad with all js-heavy sites)
If these metrics look good, then great; carry on doing what you are doing. If they don't look so good, then, they would say, reflect on whether what you are building is losing the business money by driving users away.
Someone mentioned that React is slow, it might take 200ms to update many elements.... and? Unless someone is making a fast-paced interactive game of DOM elements, it doesn't matter. Structuring the UX in a user friendly way matters infinitely more.
I hear normal, non-tech people with average hardware complain about "lagginess" of their machines all the time. And usually the only application they use is Chrome. They won't say that they had a 200ms lag when they clicked on a button, but the overall experience degrades when things are slow to respond. And when you sit that person in front of a good, optimized, snappy application, they will sing praise. Not particularly because of performance, but they will enjoy using it more, and they won't be able to explain exactly why.
You'd think that with the ridiculous amounts of money software engineers are paid to do what they do, they'd be able to swallow slightly more difficult collaboration and developer experience in order to deliver a more quality product. Forgive me for being harsh, and I don't mean this as directed to you (I don't know you), but our industry behaves like a bunch of babies.
Aside: if you're making an interactive game, you have 16ms to respond and render, not hundreds. In 16ms, modern games dispatch draw calls for millions of triangles, do AI, physics, netcode, level streaming and other bookeeping. Yet the teams there collaborate just fine.
I'm aware of those complaints. 95% is when people are using a thermal throttled old device, while the app in question is trying to smoothly animate a complete clusterfuck of a webpage (for bonus points it's usually in some god-awful WebView in an app).
It's not simply displaying new checkboxes, inputs, labels, buttons, it's multi-megabyte images with fancy CSS effects and so on.
> They won't say that they had a 200ms lag when they clicked on a button, but the overall experience degrades when things are slow to respond.
Of course, no questions there! But it's not because the "framework is not performant enough", it would be slow even in vanilla JS in 95+ % of situations.
> And when you sit that person in front of a good, optimized, snappy application, they will sing praise.
Yes. And it's because you say to the client/designer/productperson that hey, if you want snappiness even for the 99th percentile of your users (ranked by hardware), then let's test on that device, and let's forego that nice animation that you saw in that native app on your friend's iPhone 15 ÜberMaxPro.
And, not surprisingly, many of the aforementioned culprits will say "I want that shiny thing"
> but our industry behaves like a bunch of babies.
I don't think you're harsh at all! And I agree. Many IT workplaces went all-in with the infantilism. (Daycare for autist-savants! Colorful open-office with a playroom, maybe even a ball pit! You can't concentrate today? Don't worry, just play some table tennis, and try it again tomorrow! -- Contrast this with the endless office gray cubicle farms of the engineering departments ~50 years ago. Which is probably the other extreme of the spectrum. And I believe there's a healthy middle ground. Well maybe slacking off on HN is not exactly part of it.)
> Yet the teams there collaborate just fine.
The games industry is famously not in a "fine" place, I'd say :) But yes, of course, they have a clear target, and even if the process requires some blood sacrifice for the crunch times, it works, sometimes. Sometimes we get buggy things like Cyberpunk 2077, which was less-than-optimized for some target platforms.
Then indeed, abstractions a team can agree on matter more. Getting state management right matters. Hiring people and getting them productive quickly matters. Those are strong points in favor of React and even Angular, to an increasing degree for Vue, Svelte and others.
How can you know this? The only scientific way to approach this question is with real-user metrics and analytics.
And there are some benchmarks that show SolidJS and some other things are faster than React at specifically what React is doing (like dom manipulation/reconciliation etc).
And yes, I'm talking broad strokes!
For example, if you have a React-based wrapper around some SAP Gateway calls to replace the standard SAP UI then the user doesn't have much say. Because of the perceived better UX. The users of the solution inside companies (think multinationals, larger government etc) your call agent that use the React-based SAP portal can't really say I am not going to use it. Hands are tight.
The only time performance really matters when you have paying customers
I do not like JSX. It’s not worth talking about why. It’s not an argument I want to have. But framing non-JSX approaches as objectively inferior is not in tune with the reality, being that this is something sensible people disagree on.
It’s pretty hard to get more “this is my opinion rather than a statement of objective fact” than this.
> I do not like JSX. It’s not worth talking about why. It’s not an argument I want to have.
Ok.
Um… well, it’s hard to have a discussion if you won’t talk about it…
…but, “code” templates allow autocomplete and type checking in a way that is an objectively distinctive superset of text templates.
It’s because they are code.
A template is (almost always) a weakly typed DSL. Written, ignoring all the history of language design… by a bunch of folk who don’t really know how to write programming languages. …and, they. Are. Bad. Not always… but often. …because writing a language is hard, and because (reason) you can’t ever use an existing template language. Oh no. This framework has to have its own unique one, because otherwise it doesn’t integrate tightly.
Do you like DSLs? Or do they just hide the complexity somewhere else? What if the DSL is bad, not orthogonal in its feature set, poorly implemented …but cute, and useful for a very very narrow use case.
Isn’t the main critique of react that it hides complexity by moving it from one place to another?
Don’t you think it’s a tiny bit ironic that all the other templates based languages with their custom template DSLs are doing the same thing?
Anyway; I think it’s fair to evaluate template languages as what they are: DSLs.
JavaScript is a better language than most template languages by a variety of metrics. Other languages are better than JavaScript, absolutely… but, never, have I seen a template language that is.
You can love declarative configuration all you want, but it’s very very difficult to argue that just because you can make a mess with procedural approaches that they are worse; because they are a strict superset of what’s possible using the declarative approach.
…so sure. I don’t but “JSX is easier to maintain”, but it’s distinctly superior in capability.
You can argue the fact JSX better integrates syntaxes from a proper programming language makes it better than other templating languages (and I’m not going to try persuading you otherwise), but the “JSX is better than template language because it is not one” stance you’re implying won’t help you win any arguments.
That is literally the difference between JSX and most other template languages. Look it up.
The template syntax is converted to literally code and evaluated. The <> are just syntax sugar. How did you imagine the inline code works? The in-line function declarations?
Did someone invent a mini-subset of JS as DSL and a custom runtime…? Don’t be ridiculous. They did not. JSX is literally a thin wrapper around actual code.
JSX is objectively better than than the scores of custom DSL templating systems out there. If anything, I think JSX is not used and supported enough.
In the most general sense, JSX is just syntactic sugar for function composition. That it works well for html components is a side effect; it could certainly be used for more than that.
I
I guess there are specific features you find compelling: it's typed, has good tooling for completions in your editor?
These exist in other template languages, and ones that transform more readily to HTML (which is the goal, don't forget).
Maybe you also value that it has a straight-forward, well-defined transformation to javascript?
That's OK, but since HTML is the goal, it doesn't seem right to optimize for an intermediate representation. To me it's a weakness of react that you have to work with HTML as javascript (which JSX mitigates fairly well, but is hardly ideal).
If you want to have it all, try Svelte.
JSX is objectively better than than the scores of templating systems out there. You get much more: type checking, use of JS for logic, and no need to learn yet custom arcane syntax. If anything, I think JSX is not used and supported enough.
In the general sense, JSX is just syntactic sugar for function composition. That it works well for html-style components is a side effect; it could certainly be used for more than that.
I wish languages like Typescript would support JSX natively, with absolutely to dependency on any React-like library. Let me declare a function using JSX, e.g.,
type Mode = “upper” | “lower”
const capitalize = (str: string, mode: Mode) => mode === “upper”? str.toUpperCase() : str.toLowerCase()
const join = (mode: Mode, …arr: string[]) => arr.map(str => <capitalize {{ str, mode }}/>).join()
const joined = <join mode=“lower”>Bon Jovi /> // “bonjovi”I've gravitated away from React towards Vue v3. Templates are working fine, well even. You still use similar amount of Javascript (probably less).
> It's just the useEffect hook. Unfortunately that's a big problem. That hook should never have existed.
Weird. useEffect is like the archetypal hook. The problem it purportedly solves was one of the main arguments they made for hooks existing in the first place -- https://reactjs.org/docs/hooks-intro.html#motivation. They just implemented it in a clunky way, and actually the problem could have been solved in an OO fashion without going to hooks at all, but now everything is a fucking hook.
There was (and still is) a real problem in react with composability. Which they tried to solve with mixins, then HOC and then hooks.
The three main hooks are useState, useContext and useEffect . useState and useContext are very straightforward and an overall improvement on their previous counterparts. useEffect was an improvement over mixins, but it was a worse solution for class component lifecycle methods.
It was fairly obvious that useEffect had a lot of problems from the get go, but it was deemed worthwhile to add so that functional programming proponents could have state without classes and to finally have a way to use composability without the horribleness of mixins and hocs (which were worse then useEffect).
The real problem is that useEffect has it's own problems, and while we no longer have the old problems, the new problems might be worse.
So instead of "do something when this action/event happens" we get "do something when this data changes". Which ends up being abused a lot, as developers who aren't familiar with this mental model (which is most of them), tend to lump up every action into a data change.
So instead of something like (contrived example):
openAlert() {
alert("I'm an alert");
}
return <button onClick={openAlert()} />
people do: const [alertOpen,setAlertOpen] = useState(false);
useEffect(()=>{
if (alertOpen){
alert("I'm an alert");
}
return ()=>setAlertOpen(false); //if they even remember to unregister
},[alertOpen])
return <button onClick={()=setAlertOpen(true)} />
Beyond that there are multiple other problems:- the fact that useEffect (and hooks in general) is order dependent and can't be put inside branching (so I can't start an affect after an event happens).
- the fact that inside useEffect you read the data of the previous render is very unintuitive (I.E. your data is stale).
- the need to always put all your dependencies that are used inside useEffect in the dependency array explicitly - which can be even harder when dependencies are dynamic - is also a problem for many.
There's probably a few more, but that off the top of my mind.
The fact that there needs to be several eslint rules in order for people to not footgun themselves constantly is quite a red flag on it's own.
And are you sure the data in useEffect is stale? I don't think it is, the documentation[0] seems to suggest that it uses the current closure.
The rest I agree with.
[0] https://reactjs.org/docs/hooks-effect.html#example-using-hoo...
See "You don’t need Effects to handle user events".
I understand that sentiment, but it's part of the reason why computers today don't feel faster than in the past and why we waste sooooo incredibly much energy.
MobX is signals library. In other words, you are already using the signals way of doing things if you mostly manage your state with MobX. I still use MobX as well if I think I can't use SolidJS.
SolidJs if you haven't looked has MobX-like tools built in, computed, autoruns and all the same tools, it triggers "renders" when one of the signals changes. In reality it doesn't have renders, because it's not based on VDOM, but it makes it look like it does.
However I like to keep my signal library separate, I would wish SolidJS had separate signals library I could use elsewhere as well.
Also SolidJS is big library and framework by now, it comes with risks if Ryan Carniato were ever to loose interest.
Edit, I also found that Ryan has created an example of MobX and JSX without React, it's a good way to demonstrate that React is not as important with signals libraries: https://github.com/ryansolid/mobx-jsx since you know MobX that example probably makes sense.
From a brief look at their website, the downsides for using SolidJs for me seem pretty big. At the very first example, if you change it slightly you can see my problems:
const CountingComponent = () => {
const [count, setCount] = createSignal(0);
const interval = setInterval(
() => setCount(count => count + 1),
1000
);
onCleanup(() => clearInterval(interval));
if (count() % 2 == 0) {
return <div>Even count value is {count()}</div>;
}
return <div>Odd count value is {count()}</div>;
};
1. MobX let's me use objects without additional syntax (createSignal, count() instrad of just count)2. The fact that the component does not rerender and that my code does not automatically change between even and odd text means I'll probably need to have an additional mental model for writing SolidJS components. Using React+MobX I just write as I would write any other function and it'll just work (There's magic involved, but manageable magic)
Composition API: https://vuejs.org/guide/extras/composition-api-faq.html
Pinia (state management store): https://pinia.vuejs.org/
TypeScript support: https://vuejs.org/guide/typescript/composition-api.html
While I mostly stuck with JavaScript, personally I found the setup more convenient to use than working with hooks in React, and Pinia is also more like MobX than something like Redux, in that you don't have to work with too much accidental complexity for relatively simple setups. Sadly I don't have examples from that project, because it was proprietary, but the linked docs are nice.
Performance on the end-user device, especially if you're just under/over certain thresholds like 1sec to switch "tabs" or whatever you're using, does matter. Especially if you're trying to get people to buy stuff.
I wish all developers had to routinely try their products on a low-end 2-year-old smartphone. That would take the discussion of whether performance matters to a more informed level.
Same. React as a UI library is great. React as a state manager (hooks) or a framework is (hooks or hooks+next) is not good. Writing and fusing business logic to a framework is always a bad idea
Conceptually the body of your component runs on every render. If you want to have some effect on your component not running in sync with that then you have useEffect to set it up and clean it up not when the component is mounted, unmoutend, rerendered ... just when the stuff you are interested in changes.
Could you expand on this. You assert that "applications" are easier to maintain with JS, but blogs are not?
Are you defining "application" here as something with dynamic and interactive content?
Also, why is it easier to "make and maintain"? I'm not necessarily disagreeing, just curious as to why you believe this.
For apps the majority of value is functionality and that's where a lot of changes happen.
The main problem of maintenance happens where there is the most change - in JSX programming (I.E. functionality) is a first class citizen and it lends it easier to change. With templates content is much more of a first-class citizen.
Of course this is all in the margins, you can write blogs/static sites well in react and applications well in template-based languages. The tradeoffs are just a bit skewed in favor of each, and it mostly manifests when you don't have time to be disciplined about changes.
I dislike when JSX is framed as "just Javascript". It's really not - it's a templating language, just a very odd one - like its spiritual predecessor.
Personally I find JSX to be write-only and hard to reason about when looking at someone else's code.
Unfortunately, React went from less-capable and more understandable to more-capable and less-understandable model. But yeah, that's just a newbie-coder take.
1) JSX - It's terrible. Svelte, Vue, Riot... they all got it right. JSX, mixing a weird syntax of HTML and JS together is just inferior to HTML with additional markup.
2) I don't know why but every react project has crazy levels of abstraction. Everything is 15 layers deep and making any sort of change requires way too much effort to navigate 15 files and code reading to make the most mundane changes. Other libraries seem to suffer from this to a far smaller scale.
<a v-on:click="doSomething">
preferable to the jsx version:
<a onClick={doSomething}>
or even this loop example from the vue docs:
<li v-for="item in items">
{{ item.message }}
</li>
better than its jsx counterpart? items.map(item => (
<li key={item.id}>{item.message}</li>
))Then, what about conditionals? Or slots? Or classNames instead of classes? The saving grace of JSX is that it allows the creation of multiple small components inside a single file.
That's definitely not the saving grace of JSX. As I said, every react project is soooooooo overly abstracted into the tiniest little components. It's no wonder people /think/ react is slow.
<a @click="doSomething">Vue you can do
<button :disabled="!isFormValid">Submit</button>
In React I've seen people do: if (!props.isFormValid) {
return <button>Submit</button>;
}
return <button disabled="disabled">Submit</button>;
This is just an example, obviously you can write this better in React. My point is there's /always/ so much conditional markup like this in every react project I've come across or worked on.Edit: I donno how to format code on here sorry. (oh figured it out, bunch of spaces)
In JSX, the "disabled" attribute is a boolean; so it would be just:
return <button disabled={!isFormValid}>Submit</button>;The issue is people write SO much conditional logic into their react templates. Not that disabled is boolean and can be written better.
This seems to be a 'best practice' issue as well that can be avoided through PR review. My team has been putting logic more and more into local hook files to keep components clean.
People break tables up into ~50+ files. It's crazy, and everyone does this, and its an absolute nightmare to maintain. Its 100% engrained into react culture that this is the right path forward.
React will never get better if people accept over abstraction as the right path forward.
I do not understand why everything needs to be a single page application. Sure, my current employer is behind the times in the technology we use, but honestly, we survive just fine with server side rendering and plain, ol'boring, vanilla Javascript and a little JQuery here and there.
Of course, some things we have written are difficult to maintain at times, but I doubt any other library would have really made it simpler (more of an issue with the requirements than the technology). Abstraction is simple, for us at least.
I'm surprised you see that as a disadvantage, for me that's always the biggest advantage of JSX-style syntax! I don't want huge components that do everything, I want components to do as little as necessary to be actually useful. It's the same as if I were writing functions: keep them fairly small, make sure they're doing a specific thing usefully, and then compose them together like Lego bricks.
When I was doing more Vue work, this is one of the things that I struggled the most with, that splitting one component into two components required a load of boilerplate and a whole new file. (And that itself was a big improvement on Angular, which usually had multiple files doing different things, at least when I was last using it). This inevitably meant that I'd try and fit more and more stuff into a single component until it the pain of maintaining it was greater than the pain of splitting it. (At which point it would usually be a lot harder to extract the would-be child component than it needed to be, because I'd left it too long.)
I think the rest is mostly just syntax preferences. Like you say, you can write bad code in both cases, and I think a lot of it comes down to which matches better to your mental model if what HTML generation looks like. But being able to easily start a new component, just like starting a new function, is such an important benefit of JSX, for me at least.
That said, SolidJS as a whole requires a completely different mental model of rendering, even if it does look superficially similar to React. It's also a much smaller ecosystem, with less documentation, so getting to grips with it is that much harder. Very rewarding, but probably not ideal for everyone right now.
Oh, I didn't know that about Vue. Eww!
Having lots of tiny components makes it harder to see the big picture.
Too big and too small are both bad, there's a balance you need to find. Components should be small enough to fit in your head, big enough to represent ideas. The difference is that it's natural for big components to be broken down into smaller ones when their size starts to cause pain. But nobody goes around merging smaller components into bigger ones to make them more readable. When your components are too tiny people just suffer through the pain and develop Stockholm syndrome.
> I'd try and fit more and more stuff into a single component until it the pain of maintaining it was greater than the pain of splitting it
I understand that it seems painful, but this is actually a great workflow: it forces the decision to split to be based on the real pain, not on your fantasies about future pain. Pain is a tool that helps you make good decisions. In that sense React is like Perl: easier to write, harder to reason about.
This isn't a theoretical concern either. Like I said, I've had this issue with Vue before, and component sizes just bloated to the point where many pages were just single, chaotically interwoven components with dozens of state variables that theoretically were never used by each other, but in practice tended to be shared accidentally or out of short term convenience. At which point all bets are off and every bug becomes an exercise in figuring out what's going on.
That's not to say that that's a Vue-specific problem, because I've also had that issue in other frameworks, including React. But far less often in React, because it's much easier to deal with the pain when it starts with a simple refactor, than dealing with it a year and several new features down the line when everything is tangled together like a headphone cord in your pocket.
The DOM output that Lit produces, peppered with magic comments, looks disgusting though :-(
Hard disagree. Every time I work with Svelte\Vue I wish it had JSX, which is way superior to templating because:
- Creating sub components in the same file is super important. Going to a separate file, copying all the imports, writing emits, then going back and importing that file is too much hassle for a simple case where you have a carousel with cards. Refactoring is slow, components end up bloated.
- Passing down functions is more convenient than emits. For all the talk about how svelte is boilerplate free, it's equivalent of passing down a function and calling it is at least 5 extra lines of code.
- Passing down JSX elements is more convenient than slots. Every time I need to remember how to do named slots in vue\svelte I have to read documentation, while in React the mental model is obvious.
or you could try the newfound craze: signals.
I played with Vue and svelte and now a firm React user, mainly due to its ecosystem, for most products the slowness of React does not play a major role at all for me.
> People tend to compare these frameworks on things that don't matter - often it's performance.
Performance matters in a lot of contexts. If you’re doing complex stuff performance matters. If you’re a public facing site depending in search traffic performance matters.
I’ve ended up disliking React simply because it’s become this one size fits all solution that 90% of web development goes through without it ever being necessary. There’s nothing wrong with React itself but it’s often applied badly.
I think I reflect the entirety of the user base of the internet when I say "fuck you" (not you in particular, just the trend of shitting on performance so we have apps running like it is 70's and tape drives on our gigahertz CPUs) here.
You're a react guy, alright.
This also happens in the backend, but the difference is that the company país the price in the form of more infrastructure. But in the frontend is “free” so why care at all, right?
People laugh at web development, especially the frontend, for changing libraries every week but you read a thread like this and everyone is so sure that React is a bad library and we should be using some newer library instead.
I work with React daily and it has issues, but I find most issues can be worked around without much trouble. It's easy to hire people, onboard people, and if there's an issue you can be fairly sure that someone else out there has had an issue too and there's a solution to be found.
I'm not in a hurry to replace React, but I don't need to. React is stable enough to rely on in my honest opinion.
(All that said, I don't blame people for choosing React for certain classes of projects, the economics of hiring new devs, the relative maturity and stability , the large community etc all make for powerful incentives to choose React)
Yes they'll know the React part. It's the Redux/Mobx/React Router/whatever snowflake libraries you chose part that will be more difficult. I really don't like incomplete solutions personally.
React + GraphQL + jotai is my preferred stack
Needing Jotai on top of React's defacto state management is the issue. TFA talks about an ecosystem of libraries that attempt to fix React's shortcomings. Pure React does have undeniable shortcomings like proper, non-brittle routing.
I don't think jotai adds a lot of complexity though, and like I said most of the time you don't need it. It just makes syntax a bit nicer to read and write, but you could do it with context if you really wanted to.
Here's a video on how to use Jotai by writing your own in minutes: https://youtu.be/gg31JTZmFUw
All of these libraries are standard and easy to approach; when I was freelancing, my onboarding on React projects was incredibly quick, and I pushed bug fixes and features within the first few hours of joining a project. React's productivity boost is often overlooked; most developers should easily understand a fairly well-written React component connected to a Redux store.
But if we don't replace it, I appreciate if React introduced fine-grained updates and changed their attitude towards performance. I think as an industry, we have been pushing the "optimization is the root of all evil" statement beyond it's limits and now all software is super slow (except maybe games and some nice things like Excalidraw).
As I'm writing this, I noticed that Excalidraw uses React, so I wonder what's their secret sauce. Maybe recoil?
People laugh at web development, especially the frontend, for changing libraries every week
that's a 2016 meme. Things have been remarkable stable since.But other than that, yes, frontend is pretty stable now.
Frontend is still a fast moving space with a large ecosystem - and I get for some, that's not ideal. But this 'frontend fads' meme isn't really reflective of the current reality.
Webpack - 2012, Next - 2016, Nuxt - 2016, Nest - 2017, Parcel - 2018, Blazor - 2018, React Hooks - 2019, Vite - 2020, Vue 3 - 2020, ESBuild - 2020, Sveltekit - 2020
Other major languages in the backend world are at least 2 decades old (C#, Java, Python, C++, Ruby, etc).
C# with the .Net framework is an interesting example. Microsoft realized their original windows only approach was a dead end. They created .Net Core. But someone moving from .Net framework to .Net core didn’t have to relearn much at all, beyond initial config/bootstrapping, and which subset of the APIs had been implemented, because MS completed the implementation in stages.
On the flip side you have React, where you’re ostensibly using the same library for a decade, except halfway in between they made a change which completely flipped how developers weee supposed to use the library.
Because what React is as a library today, with functional components+hooks is completely different from what React was when it first came out, with class components.
React is quite clearly a name that incorporates at least 2 distinct libraries which are supposed to be fully compatible but they’re not…try using a ref for a functional component.
The existence of these 2 libraries under the same name means thst documentation is also increasingly confusing. It also means that both libraries are probably making compromises So they’re still compatible with each other on the surface.
Having worked on 3 sizable React projects now (all started before I arrived), I can only conclude that beyond a toy phase -- once you have many hands working on React and *particularly* once you start managing sizable state -- there is only pain.
The most recent case resulted in spending quite a bit of time explaining to a peer why we were experiencing an unexpected side effect and redraw and explaining how `useMemo` and `useCallback` actually need to be used [0] and made me think of Stephen King's Langoliers.
It occurred to me that "React is the new IBM" [1] It has become so dominant in the market that no one can get away from it. But that also means that it can no longer innovate. Andrew Clark's twitter post *acknowledging* that signals and fine-grained reactivity would be better for performance but that the React team doesn't care pushed me over the edge of frustration.
I think that React finds itself not too far off from where IBM was at the micro-computing revolution. IBM had become too beholden to its market and too arrogant in their own success to see their own downfall.
The traffic and feedback on the second article is an indication that there are a lot of folks out there who are really, really dissatisfied with the state of React.
[0] https://chrlschn.medium.com/8eb7bb72c87
[1] https://chrlschn.medium.com/react-is-the-new-ibm-6af2f4b04e5...
Functional components and hooks were a huge innovation to class components and significantly improved the ergonomics of the library. That was only a few years ago.
The team is actively working on RSC (react server components) which will have a similarly large impact on react's capabilities.
Frameworks like remix and next will be able to leverage and build on this to create even better systems for building apps.
The whole signals blow up event is weird to me. Seems to be a loud and extremely small minority making a fuss around it.
IMO React continues to dominate over others (Vue, Svelte, Angular, Solid etc) because its just better - it embraces JS (no v-for, ng-for, non JS language) and strictly sticks to the idea that the view is a function of state.
React continues to dominate others because it meets baseline criteria for a js framework. And has corporate backing while Vue doesn't. Angular 1 was also popular because it was average js framework with google's backing before angular 2.
Implying that React remains popular for purely it's technical merit is utter nonsense. Because if react was really technically better, then no one would have migrated to Vue, solid and svelte or angular for that matter
Fair, this instance is 100% noise imo.
We're engineers - we should be able to judge when something is silly.
> React continues to dominate others because it has corporate backing while Vue doesn't. And angular was popular for the same reason before angular 2.
I have never heard anyone in the last few years say react is better because it's backed by FB. I pick it because it embraces JS (unlike Svelte), doesn't reinvent the wheel (ng-for, v-for), and has a track record of maintaining backwards compatibility (unlike Angular re Angular vs Angular 2, hey its google what else should you expect). Class components continue to work 100%. Angular is backed by google - a much bigger company than FB and its nowhere close to as successful.
> Implying that React remains popular for purely it's technical merit is pure nonsense. Because if react was really technically better, then no one would have migrates to Vue, solid and svelte or angular for that matter
Some companies like to experiment, or have very unique challenges for which they find other tools better. I avoid Angular and Svelte - both have made such odd decisions. Some people do just prefer one tool over another! There will never be any set of capable tools where 100% of people select the same one. That's the variation of life.
Per the article's comment on forms and react and the messiness that ensues, well we're engineers. We can't expect a single library to solve every problem. We should be responsible for avoiding bad patterns like throwing from state into react state. It's 100% not necessary and should be kept separate.
The reasons for not using other frameworks seems copycat without logic. For example vue uses v-for I don't want to have to learn a handful of obvious tags like v-if or v-else but then choosing react which has adopted jsx something that requires converting standard html and learning more to get you to the same place.
I continue to pick React for projects because it's better than the alternatives - not because others before me have picked it and I'm just copycatting.
I can understand why some dislike JSX. I happen to think it's a great abstraction that elegantly combines the declarative nature of HTML and the power of JS.
It's always worth noting JSX can and is used in libraries beyond React (hello Vue!) which further demonstrates its composable nature and flexibility.
Do you avoid JSX when using Vue or other libraries that support JSX? Are you invoking the library function directly - React.createElement or vue's equivalent instead?
div('#wrapper',
div('.container',
span('.big', `It's not that hard`),
button('.red', {route: home}, 'Home!')
)
)Those are part of React, not JSX itself. Compare Vue's use of JSX, for example, which just uses `class` and `for` instead of `className` and `htmlFor`.
More on that: https://stackoverflow.com/questions/52398380/why-react-wai-a...
https://developer.mozilla.org/en-US/docs/Web/API/Element/cla...
https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelEl...
Take React form libraries for example [1], redux-form used to be the most popular by far, was followed up by react-final-form from the same authors so people naturally flocked to that. But that is now clearly seeing a decline as react-hook-form, a library that started from zero, is a lot more pleasant to use.
[1] https://npmtrends.com/final-form-vs-formik-vs-react-final-fo... (set to 5 years)
I mean, for a single version bump (Google called it Angular 2.0) to render not only the code not migrate-able, but the entire paradigms on which the framework was based on is basically unheard of in an enterprise-targeting framework.
That’s an egg-on-face technical fail.
React is not perfect, it's bloated, but the reason it took off is that it brought something new to the table as a general and programmatic way to construct UIs. Being a child of Facebook helped it achieve dominance but considering that before React we had angular (shudder) and jquery, React's success was well earned.
React will be replaced when something actually better comes along. The current contenders seem to want to return us to the technology of the past, it didn't work then and it doesn't work now.
The composition API is bliss.
What's more important with Vue and fine-grained reactivity is that it is very forgiving of mistakes and poor practices that in React would cause much more significant side effects and performance issues.
My current team is using Vue 3 with the Composition API and it is way more forgiving with mistakes than the Options API. I've helped transition 3 developers so far to Vue 3 and they all love what Vue has to offer when compared to React.
That said, as a low-level library it should not move fast; it should make sound design decisions while maintaining compatibility. It’s completely open to frameworks with more opinions and friendlier DX to be built on top of it.
I see this said a lot with particular regard to hooks, and to this day I just can't buy in.
For whatever problems class components have, they enforce a general layout of the component in a way that hooks don't. Reading some codebases that are all in on hooks feels like the wild west and is frankly nightmare-ish to untangle.
> it embraces JS (no v-for, ng-for, non JS language) and strictly sticks to the idea that the view is a function of state.
So does Solid No?
Not only can you componentise your UI code, but you can componentise your UI system meaning teams can develop independently of each other...
Usually people are not FB and people often do not have the same kind of strict development rules or enforced discipline, nor are they as many people as FB. Maybe the FB tool is not right for them.
Once you have state that needs to span your application and prop-drilling becomes too much of a drag, the misalignment between React's "pretend we're going to redraw everything" and "I'm only changing this one field in my state" causes most of the issues with React.
A junior dev isn't going to be build as fast or as clean as a more experienced dev, but a good framework promotes speed and provides guardrails to prevent mistakes.
To that end my experience with React -- same as the author's -- is that React does not have this characteristic and provides many ways to shoot yourself in the foot.
I'm not sure I'd ever expect a framework, React or anything else, to stop that behavior. If a child component signals to a parent that the state has changed then I would always expect that to cascade down the node tree. That could cause further updates. And more renders. That behavior is on me. If the framework decided not to cascade some updates that would be weird.
I think this highlights part of the problem with React and most other frameworks - people expect too much from them. If you're delegating all of your coding skill to the framework and expecting it to just magically work no matter what dodgy code design you throw at it then you're going to build a shitty app. You have to remember that you still have to think things through, use your skills as a dev, understand what's happening and why. That is always going to be true. You're always going to have to put the work in.
At the beginning of the article the author says they feel trapped by React because their previous, current, and next jobs are all going to be React based. That isn't true if they choose to put effort into learning other technologies and seeking roles that use them. If you work hard you find options open to you. Heck, they could move out of web and start writing completely different code that isn't even JS if they felt they wanted to. No one is being held hostage by React. You are only held hostage by your own fear of doing something hard. Feeling like you have to stick with React is a state of mind - you can change that with enough effort.
Isn't this the whole selling point of Solid's signals? If a child component receives its props from the parent as signals, and asks the parent to fetch some data and update the state, then the child won't rerender; only the bits that are consuming the signals will. Fine-grained reactivity, they call it.
It's not that the properties shouldn't be updated it's that in React the whole subtree gets completely re-rendered, with a potentially big performance cost. Svelte just changes the relevant bit of the DOM, like a single class attribute or whatever, and leaves everything else be, this feature alone is what made me switch. In addition to baseline performance benefits certain things which are really awkward in React (e.g. animated transitions) become non-issues.
>Feeling like you have to stick with React is a state of mind - you can change that with enough effort.
I really appreciate your optimism about switching to a different framework/ etc. and I would have felt the same earlier in my career where I didn't have so many non work commitments, financial and otherwise. But to me now this reads as wishful thinking; switching track is difficult, especially when your existing skill set represents a large chunk of the demand in the marketplace. (And I say this having recently sucessfully made the switch from React to Svelte)
Having developed with Angular and React, and dabbling with Vue, I have to say that Svelte has the best ergonomics of the lot, and the language tutorial is so approachable. I haven't had to think about performance or state to the degree that I have in other frameworks. Any workplace could easily skill up a Svelte dev from a React dev.
No doubt there are individuals with circumstances that make switching tech stack harder due to the demands on their time elsewhere, and I feel for those devs being stuck on a stack they don't enjoy (I was a PHP dev for a decade, I understand their pain). But I also think that those problems are temporary. You might be stuck on something for a few years, but in the grand plan that is your career spending even a couple of hours a week to move to something that you don't hate is worthwhile.
It'd be awesome if everyone who dislikes React could spend a month immediately learning Svelte or Solid, or Kotlin or Swift, but that's obviously not possible. All I'm saying is that if you're not doing anything to change your future then you should seriously consider if the problem is as bad as you might say it is.
Because Svelte is mutable state galore. I thought we all agreed to say no thanks to that.
Tangent: the idea that "we all agreed to say no thanks to that" is kind of symptomatic of broader issues I have with web dev. i.e. that there's very little recognition that different tools have different uses and knowing when to pick which is part of the job. Working with wood you wouldn't apply the same practices and methods to building the timber frame of 2 story house as you would to making an intricately carved toy elephant. Why when working with the materials of the web, HTML/CSS/JS, do we assume there's a best and right why to do it: "you must write tests!", "avoid using z-index!", "separate content and form", "immutable state!"; these are all the right answer in some situation and not in others.
Not to disagreed with you here, but there are many frameworks out there which either claiming themselves as "full-stack" or trying to be as full-stack as possible.
The developers who uses these frameworks might just expect "(delegating your code to the framework) is how it suppose to be used"(, while blaming people who write "raw" JavaScript code as "hacky").
This is a problem which will occur whenever you want to standardize the workflow as well as the knowledge base for your team. Some approach is discarded in this process and what's left in the end are often "common practices" which nobody has reason to reject. If the "common practices" is to let the framework to do it, then that will be that.
>Things get more complicated when you start using React Context and start signalling updates in a parent component. The render cascades. Maybe one component fetches some data, some component remounts, and you run your state update again, delayed by a few seconds.
This is just doing it wrong. State should change in response to user inputs. Ultimately, React is f(newState) => UI. If that function isn't pure you're gonna have a bad time. It's hard to blame anyone though. The docs suck and most of the tutorials you find get it wrong one way or another.
That said, there's kind of a reason why functional programming isn't more popular. It can be hard to grok and there can be a significant performance overhead. There's also a reason why this sort of implicit programming isn't as popular as imperative style. It's hard to predict what the implicit behavior is and footguns abound.
function handleChange(e){
getAutoSuggestions()
setLoadingState(true)
}^ Side effects happen in response to user input
function getAutoSuggestionsCallback(resp){
setSuggestions(resp)
setLoadingState(false)
}^ No side effects
React is not that at all. Unless your UI is very simple, React is not f(newState) => UI. React isn't functional. More on that here: https://mckoder.medium.com/why-react-is-not-functional-b1ed1...
The complicated bit is the handling of events and changing the state. Hence why you get Redux for state but there is no “Redux for views”
It's not wrong, it gives you one kind of separation of concerns: components. But "the view is a function of state" is completely misleading IMO.
useEffect is a side effect and if you use it you're gonna have a bad time.
Right.. but then you can't really use React for building serious UI.
But it’s a powerful escape hatch like rust’s `unsafe` block. Rust can do amazing things to ensure safety of your program, but there’s still times where a human can do it better.
By signposting that, keeping it to limited blocks, and wrapping it up in a safe function you get the capability to do hard things, while exposing a safer API.
useEffect is similar, it lets you write the imperative synchronisation logic. For example if you need to interact with a DOM element that only has an imperative API, someone needs to do the work somewhere to wrap it in a declarative one. You can do that in a component with a useEffect hook, and then expose a declarative API.
Because at some point your function call is manipulating registers on the CPU. If we go even further, the CPU needs to load its next instructions and then the data required.
Point being, we abstract and encapsulate complexity and provide a simpler API around it. It’s the only feasible way to manage the inherent complexity.
React builds up a virtual description of UI. react-dom and react native take that description and synchronise it to the UI layer.
If you need to do something extra, that they don’t handle like managing a map widget (ie mapbox) in React that only has an imperative API, it sure would be nice to do that yourself.
You can build a UI without useEffect. You can hide messy implementation details inside a well tested component, and contain where useEffect is being used.
And, you can understand how useEffect works so that you can use it without it having a negative effect on you.
and
"You can ... contain where useEffect is being used."
are not the same statement. Maybe I'm being pedantic, but when I read "build without X", I think there is some method that can be used to avoid X, not that I can hide away X.
All declarative code eventually runs something imperative.
And anything non-theoretical is going to have side effects somewhere.
Painting to a screen is a side effect.
Reading a file is a side effect.
Software gets messy when it intersects reality.
But, we can do quite a lot by staying in a theoretical realm. You can build a whole UI in the theoretical realm, where no side effects exist.
When you actually need to run it though, you drop out the the theoretical and into reality. Now there’s side effect’s everywhere.
So you contain them. Encapsulate those side effects into composable blocks. Test them extensively. Offload that work to someone who’s just focussed on managing them.
Updating the DOM is a side effect. Making a network request is a side effect.
Contain them, test them, and then you can stop thinking about them.
If someone else has done all the work to contain side effects, you can build a UI without them.
Why would fetching data depend on whatever is being rendered?
You know what data you need or not need before rendering anything, or you will be in a world of pain.
- Click the link to show top scorers
- Initiate fetching the data
- (The view may change to indicate you're loading the top scorers, if you want, that's a different matter).
- Receive the data, the view changes to display the data
This is opposed to:
- Click the link to show top scorers
- View changes to show top scorers component. A component loads, or mounts, or inits, or does something which triggers a data fetch
- Receive the data, the view changes to display the data
Your app "knows" you need the data when the user clicks the link, no need to involve the view components into this.
This gives you the ability of adding a lot of complexity to how you fetch the data that is best handled outside a UI component (like caching, reusing it in other components, error handling, retrying, throtling, whatever), while saving you from a whole class of problems where a misunderstood component lifecycle has consequences for your data. Frameworks like React or Angular are going to try to help you by caching outputs, reusing components, dropping updates for the same frame, prerendering, preloading or anything really. If you fetch data when a component does any of that, suddenly you have to care about it and fully understand it. The abstraction leaked. If you treat the component as close to a pure function as you can, things become much simpler.
This applies to relatively big, relatively complicated apps, controlled by a single entity, where it pays off to prioritize simplicity.
- how is the data fetch completion signalled to the component?
- how is the data piped into the component?
Would be happy to be pointed to some example code if you have.
Both have the same answer. When you fetch the data you put it in the state, and then you render your components based only on that state.
If we're talking React the state makes it into the component through the props (pure UI component) or, if using Redux or similar, some kind of hook that triggers a rerender when the store changes (useSelector? My React-Redux is a bit rusty).
The point is not to worry anymore about change detection and rendering, because the framework takes care of it by being either fast enough that it can run on every change, or smart enough that it can tell when it's not necessary to re-render (caching, change detection).
Of course, this setup with redux etc makes a lot of sense for bigger apps with lots of state coming from different sources. I don't have any specific example I can point to, but any redux implementation examples could help. I use NgRx with Angular, and the docs are OK at explaining the flow of data.
> But then they added hooks and useState and useEffect and so on, which made the functions impure. The problem with hooks is that they “hook into” React state and lifecycle features, which means it is modifying global state.
React components don’t update the dom every time they run, they update the fiber tree / virtual DOM.
Only in the commit phase is the DOM updated and side-effects are run.
My rough understanding is that:
Hooks, excepting useEffect, all run in the render phase.
UseState hooks store data in the component in the fiber tree, and capture a sequential list of updates when you call setState.
Algebraic effects can seem a bit odd at first, but it’s really like a generalised try/catch. Instead of storing state in the function itself, you reach out up the stack to the component and store it there. And every hook you call from your hook stores it there too.
It’s why call order is important, because it’s how they know which is which.
You don’t modify any global state though.
The actual component function needs to be able to be called multiple times in the render phase (which just updates the vdom), and must have the same output each time, if the inputs/props are the same.
Every now and then, the tender phase can be interrupted to run the commit phase, which synchronously brakes a snapshot of the vdom and applies all the needed updates to the outside world.
Perhaps it’s better to think of as
render: f(props) -> descriptionOfUI commit: apply(descriptionOfUI)
I would absolutely say components and hooks are functional, with algebraic effects. And that the resulting data struct from those components, is what’s used to produce side effects.
Even useEffect, is a description of a side effect to run, it doesn’t run in your hook, it runs on commit with all the other side effects.
There’s a ton of optimisations under the hood but that’s roughly my understanding of how it works.
In functional programming, functions are not allowed to do that. The only thing a function is allowed to do is return a value.
> ...you reach out up the stack to the component and store it there.
FP functions are not allowed to do that. In FP functions can only rely on the parameters passed to it (it cannot refer to anything outside) and it should not do anything beyond return a value.
> It’s why call order is important, because it’s how they know which is which
In FP, functions can be called in any order (unless one function needs the return value of another), and the final result is not affected by the order.
> You don’t modify any global state though.
If you have state it is not FP, whether it is global or not.
Oh, yes, they are allowed to do that. You capture the effects into a list, and return the tuple of list and return value. If you feel like it, you wrap that into a monad to pretend you are only "returning" a single thing.
> In FP functions can only rely on the parameters passed to it (it cannot refer to anything outside) and it should not do anything beyond return a value.
You mean explicit parameters (props) and implicit parameters (context), right? I thing you forgot the latter. Implicit parameters have existed for quite a bit, for example in the reader monad.
> In FP, functions can be called in any order (unless one function needs the return value of another), and the final result is not affected by the order.
Yup, except if you write a bunch of functions and store them in a list with the intention of applying the result of the first entry of the list against the first entry of the list. Now, if you construct the list of functions as effects (by hiding them behind a monad) you find out that you need to call the effects in the same order as to construct the list of effects in the same order. This doesn't contradict FP, it contradicts your mental model of how React is supposed to work.
> If you have state it is not FP, whether it is global or not.
The state resides in the runtime executor, exactly like Haskell's IO monad. Again, this contradicts your mental model, not React or FP.
You keep the clarity of declaring what you want to happen, and abstract the how to the effect handler.
Take a look: https://github.com/wisercoder/eureka/tree/master/webapp/Clie...
You just need to know JavaScript, HTML and CSS, not much else. The code is simple, and yet maintainable. No need for hooks, useEffect, useState, useMemo and all that crap.
I can’t really call this code simple since it had to resort to timing hacks to get its functionality in order. A random 250ms delay and bam, bugs you cannot reliably reproduce
private onDropDownMouseOver(ev: MouseEvent): void {
if ((new Date()).getTime() < this.whenScrolled + 250) {
// We automatically get a hover event when we scroll, ignore it in order to keep our current highlight.
return;
}
const element = ev.target as HTMLElement;
if (element.classList.contains('combo-dropdown-item')) {
addClassExclusively(element, 'combo-highlighted');
}
}
Some event stores the time it has been fired, and this method checks that it has not been long since the firing. With react, which item has the highlight would have to explicitly be in the state and completely remove the need to do this optimization.And this is an example of what I consider state being stored in the DOM:
private isDropDownVisible() {
return isVisible(this.dropDown);
}
The view has logic that depends on whether the dropdown is visible, which is checked by dropdown.style.display !== none. Now any element in your page has the power to modify this component’s logic by modifying the DOM> Now any element in your page has the power to modify this component’s logic by modifying the DOM
If some part of your application intentionally does something wrong, it can break your application whether it is React or some other tech. In this particular example, if you prefer, you can have a member variable to keep track of whether the dropdown is visible or not. Still no need for React.
As you can see, none of the complexity of React is necessary. No need for hooks, useEffect, useState, useMemo and all that crap.
The code does not have any complexities of hooks (which are just a javascript approximation of do notation, I don’t believe it is that complex), but what it does have is the requirement to write down all of your mutations correctly, where every “down” is an exact opposite of the “up” and does not leave any artifacts—with no way of formally checking. At least for myself, I think that level of discipline is unreasonably high so I tend to prefer stricter typed functional solutions where the view is composed purely from the state
I love how you do React. I mean, what's more react-y than blanking the page then appending HTML? I'm gonna call that Rejqueryact, because it's jQuery inside React.
Is this really much more complicated to implement than the equivalent implementation in React? (It's probably a bit more responsive, at least.)
The comment was a reference to the fact that if you don’t use a framework, you’ll end up a building one anyway.
The code you linked is what React helped me get away from. There’s multiple files in different folders for one screen. It’s hard to see how it composes, which is a useful boundary as it lets me know in the scope of that part of the UI.
UI is _hard_. There’s complexity that needs to go somewhere, and I’m one of those who prefer to push as much if it that isn’t business logic into a framework.
This becomes exponentially more important for every engineer you add. Go success is along these lines, with typically only one way to do things it’s much easier to share code.
From the code you linked, I could find my way around, but piecing it all together took a lot more work than any of the frameworks.
You mention only needing to know JS, HTML and CSS. But you missed that you still need to know how all that code is put together, what calls what. How it updates. React needs this too, the only difference with it being a framework is that knowledge transfers to a different project.
And to be clear, I’m not saying you need to use react or a framework—going your own way is often how amazing new things are found.
What I am saying is your attitude isn’t helping you here. React is still arguably the most used framework[0]. There’s a reason so many of us like using it and it’s what you described as “other crap”.
Frameworks help with collaboration, in the same way programming languages do. To do anything interesting with a general purpose language, you’re either going to use a framework, create a new one with good documentation and build a community of engineers around it, or build a halfbaked one that few people understand.
I’m open to other ways of doing things. It’s a good way to grow. I learnt SwiftUI a little while ago, and while I don’t use it regularly it improved my understanding of UI building. I learnt imperative UI API ages ago, and know for sure I want to avoid/contain that into a more manageable declarative approach.
[0] https://trends.builtwith.com/javascript/javascript-library/t...
We didn’t have classes until ES6. And they’re not real classes, they still use prototypical inheritance under the hood.
If you want truly idiomatic JS, you shouldn’t be using classes. You should only be writing functions, and build your class-like objects with prototypes.
On a practical level, I absolutely recommend new engineers learn React. The job market is enormous, it’s a skill the market still rewards well.
And it’s a very productive framework. It rewards you for learning it, with better collaboration and velocity.
I would say the same for the other major view frameworks too, but React still has the biggest job market.
Until ES5, the industry thought JS was a Frankensteinesque monster.
Until maybe 5-7 years ago, anything that wasn’t OOP was considered a bit weird.
Calling any of these languages weird, is like policing English speech. We borrow so much from other languages that’s words have multiple meanings. Pronunciation follows contradictory rules, and regional dialects can be hilariously incompatible.
There’s a few languages closer to French, which has a strict control on what the French language is. For example, Go. There’s really only one paradigm them, only one way to do things.
Like it or not, pushing the boundaries of language design and framework design is how we improve as an industry.
You can’t not like a new thing because it’s weird at face value. You risk missing the forrest for some moss on a tree, and being left behind.
And sorry, that’s the same article this comment thread spawned from. I didn’t find it convincing at all, it’s let down by a lack of understanding in a few key areas.
For exactly the same reason OO is "put the code that manages the state near to the state and split it in manageable parts" and not "dog inherits from animal therefore the code is correct".
Leave the faith at the church and approach code with science.
If you’re fetching some data in a useEffect you might not get a result that day.
If you’re updating something with setState, you are still managing state. UseState is a reference to a mutable object now.
You’re simply not getting the same answer every time your now impure function is called.
In order to do understand what’s happening you need to recreate the whole state. Which is exactly the same reason state management is hard as in OO or procedural.
You might have a mental model that explains why it is still FP, but for all practical purposes of that paradigm it isn’t.
When you reply to "in FP, functions cannot do that (change state anywhere)", you say "you are allowed to do that: capture the effects into a list, return the tuple of list and return value" without realizing you're saying exactly the same thing?! The distinction between "return value" and "return value plus some other thing" does not exist. What matters is that the function's only observable modification is in what it returns, be it one value of many. This is basic FP.
The function's only observable behavior is that it returns a tuple with JSX and some effect descriptors.
No, this is not basic FP. This is somewhat advanced FP.
function MyComponent({}) {
const [count, setCount] = useState(0);
const [active, setActive] = useState(true);
useEffect(() => if (active) setTimeout(1000, () => setCount(count+1)), [count, active]);
...
can kind of be thought of as if it accepts an extra hidden set of parameters, kind of like this: function MyComponent({}, hook1 : useState, hook2 : useState, hook3 : useEffect) {
const [count, setCount, hook1Result] = hook1(0);
const [active, setActive, hook2Result] = hook2(true);
const hook3Result = hook3(() => if (active) setTimeout(1000, () => setCount(count+1)), [count, active]);
...
return [<div></div>, [hook1Result, hook2Result, hook3Result]];
}
In this version, those hook functions are side-effect free, pure functions that our caller provides us with, closed over the previous stored state of our component in the tree; and when we return the results along with our rendered output, our caller has the new state of our component together with our desired DOM.Instead of forcing us to write all that extra code, route those extra variables, and figure out the metadata mechanism whereby the caller of the render method figures out what hook functions to supply, the rules of hooks let you use JavaScript's imperative, procedural syntax to call hooks which are implemented using ugly side-effecting impure techniques, but in a way that pulls off something semantically identical to this pure functional flow.
It's a pretty neat trick, honestly.
Because web browsers exist, and they work in a nonfunctional way.
So to interact with one we need to do a little bit of imperative code.
And then react lets us figure out what to do when the web browser responds to that imperative code by letting us run a largely functional program.
Which is pretty neat considering we’re doing so in JavaScript.
The thing that we’re after here is not a badge that we can slap on our code saying ‘certified 100% functional’. We are trying to write code using patterns that help us reason about and structure what we want the computer to do, avoid bugs, and ship software.
If react managed to squeeze a surprisingly functional pattern into a JavaScript library to that end, can’t we just applaud the audacity and enjoy using it, without nitpicking that they didn’t actually reimplement the lambda calculus?
React is neither FP nor OOP. More on that here: https://medium.com/codex/can-we-all-just-admit-react-hooks-w...
React builds on functional reactive programming, something the FP world is known for[0]. I’m not saying it’s pure FP in the dogmatic sense, I just wanted to point out it’s closer to FP than the other paradigms.
Without the ability to interact with the outside world (side-effects), FP is not of much practical use. Not to say it’s bad or shouldn’t exist, just we need to add to it a bit to make it useful.
Why would we do that? Because the underlying ideas and principles provide a great foundation. Building on that to get FRP and algebraic effects, monads and so on, is very different to starting from OOP and brining FP ideas over.
React hooks are an interesting and tricky thing to put in a box, because they’re almost monads, almost thunks, almost algebraic effects. The interplay with fibers and components makes them hard to pin down, but they are much closer to functional than any other paradigm.
[0] https://wiki.haskell.org/Functional_Reactive_Programming
What we have with badly written React apps now (90% approx.) is a UI, that is not at all behaving like a typical website and very far from being like FP. We often cannot simply go back with the back button and expect to see the same page rendered. I mean we can, but the websites will fart in our face, if we do. We do not get the ability to simple send a link to someone and have them see the exact same page. It is a huge departure from anything FP.
Furthermore from the dev perspective components feel more mainstream OOP than FP, since they store internal state and update it, which indirectly causes things I described above.
Not sure where people see the FP. Not sure they really have done any FP language before or tried in projects to strictly adhere to FP principles, because that looks a lot differently than React components and mixing state, layout and styling in JSX/TSX.
They're almost classes (/objects). The implementation is what it'd look like if you wanted to make a weird half-assed OO... thing. Property and method declarations, getting attached (ultimately) to an object. But it's FIFO access/calling, rather than using named properties and methods w/ a lookup step. And the declaration syntax is bizarre and hard to read. And they're slower than regular JS OO (because they add an extra layer of JS on top of it).
The bit that is g(state, userInput) => newState is the hard part. In particular managing the scope of that newState.
Oh, and sometimes you need to handle h(state, asynchronousData) => newState too.
And then comes the fact that even though your f is _pure_, it also has to be _fast_, because it's going to run every time you get a newState.
- https://redux.js.org/usage/side-effects-approaches#recommend...
What I like about sagas are their simplicity & power (once one understands how generators & effects work), plus the eventChannel feature which lets one integrate with non-redux events. Good TypeScript support is a problem though, and I've had to resort to typed-redux-saga :/
- https://redux-toolkit.js.org/api/createListenerMiddleware
- https://blog.isquaredsoftware.com/2022/03/designing-rtk-list...
Event channels was something we intentionally _didn't_ try to replicate per se, and tbh I've never tried to use those myself. (But, I _suspect_ that you might be able to do something similar with listeners even though we don't have a specific replacement built into the listener middleware, and if you do I'd love to see an example in action!)
If you get a chance to try out listeners in your project, I'd definitely appreciate feedback on how well they work out for you - whether they solve your current saga use cases, what cases they _don't_ handle, anything we can do to improve the listener API, etc.
Sagas keep state (and you should keep most state in the redux store, anyway).
So, yes, you can go wrong, as with everything else. But it's better than using useEffect as an async framework.
Remove most logic from the components into sagas,thunks and selectors.
That way your components will be smaller, more testable, easier to change, easier to reason about.
It's like you're speaking a different language to me, and I find that so weird considering we're using the exact same framework. How am I not having any of these issues?
I'm honestly at the point where I wonder if y'all are making things harder on yourself somehow, because I could see how getting obsessed with counting every single re-render and trying to overoptimize would result in the stuff you're saying while not actually impacting perf in a meaningful way.
When I do encounter a component with countless re-renders as described, it is usually painfully obvious what causes them and easy enough to fix.
I think we're going too far if we're expecting React, or any framework, to be fool-proof to the point that we can just throw "whatever" we want at them and expect it to have peak performance.
Timing-based UIs are (such as a sequence of triggered animations) can get really messy really fast. I've seen some really messy bugs in a app that had visuals and audio tied to different timers and user inputs in the app. We eventually moved all time-based animations to observables, which helped some
Something I don’t quite get, doesn’t useRef just solve the re-render issue?
I had to eventually claw my eyes out and that solved part of my problems, at least I did not see the boilerplate and the ugliness.
Then soon after that we worked on a similar thing (form + draggable carousel with snap to grid animation) in Angular with Material.
And my conclusion is that whichever framework you pick, whatever libraries you end up using, you must have a strategy to allocate your time and maintenance budget, and many many many times the sane compromise is to write something in raw JS and encapsulate that in whatever the framework gives you, and move on. Don't try to solve it within the framework, because it's just not worth it.
I don't know if we have any "timing" based components, though we manage global state using Apollo Client and again, haven't really had any issues with that.
Your app is the store, not the DOM.
It really makes things much simpler. The trick is to keep all the state in the store, including when things are loading, when some user interaction is happening but not yet complete, etc.
From your comment, it seems like there may be some problem if the user is interacting somehow, let's say in the middle of doing a drag and drop, and some data update comes in from a websocket, right? Well, if that's going to cause a problem for your render it's because apparently your data-updated function h needs to know if the user is doing a drag and drop. That should get put in the state when the user starts the interaction, and now h can know about it and react correctly.
Yes, it's more complicated than just have some component render based on the data you receive, but that's because it turned out that your app was more complex than you thought, it has more states you need to care about.
There's no magic wand, but this stuff works, just adds some boilerplate code but I don't mind.
Didn't have to in the past. Back with class-based components we had shouldComponentUpdate(), and lost that when components switched to pure functions.
Absolutely not only to user inputs, but any kind of event: response, websockets, push notification, worker task finished... a million things beyond the basic "click".
> If that function isn't pure you're gonna have a bad time.
Hooks let you deal with "component lifecycles" which make that function not pure. Only the most basic toy react components are pure, everything is about side effects IN your views.
The clue is in if everyone is missing the point but you, may be start with more introspection. :)
I will give an example of a side project I am working on. The homepage has two sub components, one when the user is logged in, one when the user is logged out.
Now, when the user logs in, the state of the homepage parent component needs to change, the state of the nav bar needs to change etc.
Your problem is in assuming newState is completely described locally which isn't always the case.
React had some obvious red flags; it seemed unwise to re-render entire components each time and regenerate the DOM instead of trying to work with it; it's a hack. It's not difficult to think of scenarios were it fails; for example think of what happens to an element's scroll bar after it has been re-rendered from scratch; it resets... Yet people kept coming up with workaround after workaround to all these kinds of issues. If they had tried PolymerJS (which was going for a native Web Components approach and interfaced nicely with the DOM instead of bypassing it), they would have questioned React's merits. When the useEffects hook was introduced in React, to me, that was a vindication of Polymer's stance (which it had figured out years earlier) that you couldn't completely pretend that DOM elements don't exist, yet React's solution was not as elegant as Polymer's as it was tacked on as an afterthought rather than as a carefully thought out design decision.
Nowadays, with native Web Components (HTMLElement) in most browsers, I don't see why people would still start projects with React, especially given the massive number of dependencies it typically introduces and how often they keep changing stuff and breaking compatibility.
They promised a simple component library which would be the answer to our prayers. What we got instead is a 7 year religious pilgrimage which involved a million developers simultaneously trying to make sense of it; attempting to discover its true form by inventing abstraction upon abstraction and growing increasingly fanatical as it devolved into a wicked monstrosity which should have brought the wiser among us to our knees, begging for JQuery.
To this day I can immediately tell that an app was made using React once the first focus/selection bug rears its ugly head.
I’ve always thought React was some sort of mass hysteria as well.
We can agree that state management is complex, no matter how it’s done. If you disagree, cool go build a database.
Of all the complexities around state management, the one squarely placed at the top for me is: time.
State is a variable you care about, that will change over time.
Signals and Hooks/Effects present two very different approaches to the problem.
They both require updating your mental model, and they both have specialised tooling.
Myself, I’ve never fully grokked observables/signals—particularly in relation to a UI. They shift complexity into a location that I think makes them harder to reason about.
I did take to the React approach with Components and hooks. And in my experience so did many others.
I disagree with the article saying all frameworks must have signals, and I appreciate the React core team holding their ground on that.
It’s healthy for the ecosystem to have frameworks built on different ideas, otherwise why build a new framework?
But React, if you added signals I think you would warp it’s entire foundational paradigm.
You don't want to rerender? Use useEffect with an empty array! Or don't use any state variables!
You want to show something new to your customers / users without rerendering? Well sorry, that's impossible, regardless of any framework you use and you should go back to UI development 101.
Bottom line: if you write clean code and are aware exactly of what your local state / redux variables are (or whatever state management you are using), you should never have a problem with too many rerenders. I've been writing React for 6+ years now and have NEVER had to reach for useMemo or useCallback.
But this problem existed before hooks: old school React devs will remember the days of class-based components with humongous componentDidUpdate methods peppered with calls to this.setState(...) that did the same thing.
My own impression is that hooks offer better lifecycle controls overall, with the side effect (heh..) of handing devs an arsenal of footguns that will inevitably go off if they don't fully understand the hooks or where to use them or how React detects and triggers a re-render. So in a way I agree with the author of the original article here, but in the sense that React devs should probably not use hooks until they understand how re-renders happen and why to avoid that and only then should they be handed one footgun at a time.
Compare that with Vue composition api, and you can see how idea of hooks can be implemented much better[0]
[0] https://vuejs.org/guide/extras/composition-api-faq.html#comp...
When you say “render” are you referring to what React means by “render”, that it will go through the whole virtual DOM cycle? Because it most certainly is possible to avoid that when using pure JavaScript. Why do you say it’s impossible? React’s fundamental problem with performance, and the whole reason people often don’t want to re-render is because React renders everything, then does a big diff on the DOM to compare it to what was rendered before, and then updates the elements that changed. I know a lot of work has been put into making that process fast, but it’s still really expensive compared to the pure JS way of doing it. In CS terminology, updating a button or any other single element went from an O(1) operation with JavaScript to an O(N) operation with React.
My point is that updating the state for a single element causes React to compute the state for the whole page, and diff the whole page virtual DOM against the whole page actual DOM, before pushing the update of that single element into the DOM. With pure JavaScript, you can skip all that and directly update a single element. This is often in practice much faster.
Wha- how?! The moment a useEffect depends on a callback, it needs to be memoized!
The quickest obstacle you’ll run into as someone new to React will be something like this
function MyComponent() {
const [num, setNumber] = useState(42);
// infinite loop
setNumber(n => n + 1);
return <div>{num}</div>
}Trying to make state updates at the top level of a component will result in an infinite loop.
```
I've taught React to dozens of people without ever seeing someone try this. A render function is an idempotent function that produces UI for a given state, and it's called every time the state changes. What are you, semantically, trying to do by updating state midway through a render function? This isn't a footgun, this is the author picking up a screwdriver and going "I wonder what happens if I press it against my eyeball"
I like how you say "others might not be so diligent to have read the docs"... As opposed to? Picking up a UI framework and just winging your way through LSP autocompletions until something happens on your screen?
Yes, that, and following bad tutorials by other people who did the same.
I... isn't it? Isn't this like the first thing in the hooks introductory material? If you don't find this, yeah, hooks are gonna be a bad time.
> Line 9: When the user clicks, we call setCount with a new value. React will then re-render the Example component, passing the new count value to it.
https://reactjs.org/docs/hooks-state.html
I think they assume you'll figure out that it must do so to function at all.
For the longest time React was kind of in denial to a large degree about what they were. They called themselves a View library. Hooks have definitely noticeably changed that relationship, & how people integrate app state with React, but the problem here of updating hasn't really changed all that much.
It's not a new thing either. A lot of the initial resistance to React & the VDOM was that it felt like unnecessary work. Because so many frameworks at the time were working towards two-way data-binding systems, which aren't necessarily but were often associated with with smaller, precise DOM updates. HP/LG's WebOS's underlying Enyo project was one high profile would be effort here.
Signals have definitely been a good re-grouping point, for reconsidering what the shape of things might look like, for trying to do a better job.
I'm a bit surprised we're still operating so much at a library level regarding reactive systems/signals. JavaScript objects have quite a lot of flexibility already, and the addition of Proxies added a lot of capabilities. Faint/distanct memory, but I think Proxies were justification for killing Object.observe[1]: now users could do whatever they wanted, so we no longer needed a JS native way to see objects change. Yet, we're still very library based, rather than trying to make objects themselves better, more reactable.
[1] http://web.archive.org/web/20200218195131/https://developer....
React has no real answer to state going sideways.
Then there is controlled/uncontrolled component which is an example of structural instability (what looks like a tiny change to your boss is a bigger deal than it should be) unless you ride the crazy train and use “plain ordinary javascript” to build a parallel system to move (some of) the state around.
Instead, it feels like most state management libraries ultimately end of writing their own Chrome extensions. Which now that I say that makes me curious: do any of these executions also let you observe/monitor server-side state management systems?
using links to refer to information is, like, not a totally foreign concept to the web (and certainly granted: in some cases this issue of signaling via url can get quite ugly; but often it's not).
To test the context itself: pass as children of the context components to render the context state.
To test the components within the context: create a context with mock functions/values.
React has no answer to state going sideways because React manages a tree of components, and you are not supposed to connect random branches of a tree. That would completely break the concept of tree, container/contained, and just convert everything into a graph, and graphs are much harder to deal with. BTW, HTML is a tree, not a graph.
Controlled vs uncontrolled and the boss demanding a tiny change is just another case of bosses not knowing about how it works the system and imagining things and then demanding reality to conform to their imagination. Not an issue with React.
One where the event originates (knobs), one where it will gets translated into actual UX effects (DOM updates, API fetches, whatever, lets call these servos and gauges), and one place where the business logic lives that transforms between the low-voltage input signal and the high-voltage output driver power.
Without that transducer you have incompatible things.
Yes, many times this is a trivial thing, and that's usually when it can be done internally to the component.
For relatively simple applications you can push all the state high up to the root of the tree or near the root of the tree and have it flow down with props.
There is a complexity hierarchy and around the time people woke up to AJAX (there were a few years when it was just a ‘evil Microsoft thing’) I was writing apps that were highly dynamic, the extreme example is an IDE with property sheets or something like Adobe Photoshop where an arbitrary number of components need to ‘react’ when a piece of data changes. It is bad enough when there is a status bar and four other parts of the UI determined by management that need to be updated when a piece of data changes (could become five or six tomorrow). it is worse when the user can instantiate arbitrary components (say for a knowledge graph editor or a geospatial intelligence tool) that ‘listen’ to event changes.
Prior to 2010 I was building apps like that and developing special purpose frameworks to do exactly as you say in GWT, Silverlight and such. There was no support for such things at the time, no async/await, management and other devs had no idea of the ‘race conditions’ that could happen when data could either come out of a cached copy or get fetched.
In those cases I spent a while struggling to understand the problem and developed systems for handling state in complex applications so when I look at React, Vue and most of those (with the possible exception of MobX) I want to ask “where’s the beef?” because these frameworks are not adequate to the problem and people don’t seem to understand they are no adequate to the problem (it comes from Facebook, how bad can it be?)
Most of the reason why people think "React is OK" is that they are writing apps (99% of them) that are so simple they don't need React. If you're writing apps that really need React, than React doesn't seem OK.
Your application is effectively "anything can modify anything", which is the previous step to "anything modifies anything", I/E big ball of mud. React's answer to that is "keep all the state in a small component" (small ball of mud) or "keep the state in a tree" (one-direction bindings, prevent state graphs).
This makes React discourage (I/E makes harder and puts friction) graph-based state, as it is the most direct path to big ball of mud.
This doesn't solve your problem, but definitely helps push 99% applications away from the big ball of mud. The fact is that for your 1% case you need the big ball of mud, and, in your case, pushing away from it doesn't help.
In those two applications I joined failing projects that really were a "big ball of mud" and got them working. I didn't just figure out a working solution to the async updating problem, I became intimately familiar with seductive non-solutions.
The problem with the discussion about React is that 99% of the use cases of React don't need to be an SPA. If it's possible to SSR your application you don't need React! Those applications I worked on were dramatically more complex than today's SPA because they needed to be SPAs!
Back in the 1990s people would define a web form in a static HTML page and then write a separate CGI script to handle the form. If there was an error in handling the form the CGI script was unable to redraw the form with an error message and the values filled in because the CGI script didn't contain the form.
Around 2000 or so people realized the answer to this was for the form to drawn by the same script as the form handler, and the script would choose to either draw the form or the next thing after the form based on the inputs it received. Ruby on Rails institutionalized this around 2005 and misappropriated the name "model-view-controller" for this.
Not long after 2010, for reasons I still don't entirely understand, the web design shops in my county transitioned from successfully writing quality RoR apps to attempting to write "simple" Angular apps. How to do error handling for forms on the server side got forgotten like the formula for Damascus steel and instead people started writing SPAs to do what would have been a trivial task in a server-side application except now the application is "a tiny pebble orbiting a supermassive black hole made out of dark matter".
People who are happy with today's SPA frameworks are happy because they are developing applications that don't need to be an SPA. Once you get into the range of applications that really need an SPA they let you down.
Everything can be done with SSR, but some things are terrible with SSR (oh, you need real-time updates? have some meta http-equiv refresh header, and observe the beauty of the page going blank and re-rendering every second).
Before you ask about the developer experience: it's about having developers that can focus their brainpower into animations and interaction design without having the expectations of having to know SQL.
Or look at https://www.phoenixframework.org/ to see what a web framework would look like if real-time updates mattered. (That said I do find that simple IoT applications like a volume knob for my smart speakers in party mode or that can toggle my lights do work well with websockets + mobx + React.)
As for DX, I think waiting for "npm run start" to get out it's own way is a large enough decrement that I don't have to get into all the many problems w/ JS build systems.
I will grant that React is nice for an animation-heavy UI and I play video games enough that I appreciate such things. Another thing I like about React vs similar competitors is that the rendering model is flexible enough to enable things like react-three-fibers which is another reason for me not to invest in Vue, Svelte and things like that.
As for user experience isn't it the dark truth that Google and Facebook want "as many UI redraws as possible?" Let's face it, the honest clickthrough rate on ads is indistinguishable from zero but when you visit some site like anandtech it is by no means accidental that the layout rerenders endlessly because each rerender is a chance that a click on a link is transmogrified into a click on an ad. It's covert click fraud and is a large enough decrement and between that and the endless staring at spinners and waiting things to load any possible increment in user experience is at best hypothetical.
(e.g. in another window I have a completely SSRed app that uses HTMX. It uses zero spinners, runs as fast or faster than a desktop app, and never has the UI move around mindlessly. I grant it would be cool if it had some more animation but would I trade that for rock solid responsiveness?)
And yes, Phoenix is a very interesting thing, but it's most likely only viable because of it being Erlang under the hood (needs a process running for each client, hence ultra cheap Erlang processes being a good fit).
> when you visit some site like anandtech it is by no means accidental that the layout rerenders endlessly because each rerender is a chance that a click on a link is transmogrified into a click on an ad
I think you went a bit too far into the conspiracy theory there. An element for which the height is not defined (via HTML or CSS) gets rendered usually to 1x1 pixel, which forces a redraw if the element turns out later to have width and height (like an image that takes half of a second to download). Which, IMO, means web developers are not bothering to put sizes in delayed-loading elements, which points a bit more to the incompetence side than the malice side. But ads probably not specifying width and height would also indicate significant malice, can't rule that out.
So, I always "hated" RoR, because it was full of hidden conventions and regular black magic. At least PHP was globally simple and primitive, even if locally ugly and complex.
I still remember Misko's early(est?) Angular announcement video, it was just part of GTAC [google test automation conference], and the whole thing was about testability.
https://www.youtube.com/watch?v=gQclnI_8Vmg
It was seen as natural separation of concerns, it was seen as - finally - breaking free of the big bulky backend (of GWT and the shackles of semi-autogenerated frontend code) the frontend runs on the browser anyway, it needs to manage its own state anyway, etc, etc.
Of course this only emphasizes your point, that a good ~95% of the sites are not like this, they shouldn't even try to manage state on the frontend.
> Once you get into the range of applications that really need an SPA they let you down.
Yep. I wholeheartedly agree.
The problem each of them tried to solve, and continue to try to solve is purely lexical in the end. It's about writing things differently. Creating abstractions (terms) beyond what the underlying language/platform allows you to do.
And this is not a bad thing. The solution really is to create your own language so you can express the problem you are solving in the terms of the problem and not the underlying language/platform/hardware.
And then I sigh again... aah but if only Common Lisp and it's macros were the underlying platform.
That's what Elm is about. I've talked about it in another thread, so I won't repeat myself here.
DSLs also usually are an incomplete solution. Unless they themselves allow adhoc language creation using the DSL as a base. Common Lisp with its macros allows writing DSLs quite off-handedly as you program. You grow your program and language together as you get deeper into your problem.
Being able to use such similar concepts/knowledge for both web and mobile, with strong results in both places, that’s something React is uniquely good at (AFAIK), and a huge reason to choose it IMO.
[0]: https://quasar.dev/
Checked, yeah. Using Cordova or Capacitor. They say it looks native, though? No idea.
> What I like about React/React Native is that it’s web-native components on the web, mobile-native components on mobile, so you get true native look/feel/behaviour in both places.
Oh, that is cool. I never worked with anything mobile, so I didn’t know. I will read into that, not that I plan to use it, but it sounds interesting :D
But React/React Native is the only mature/popular web/mobile approach I’ve seen that embraces web components on the web AND mobile components on mobile, which I think is a big advantage. Though maybe there are others I’m unaware of!
I’m sure there could be React Native like solutions for other libs/frameworks, but I haven’t seen any that are as mature with the same “native components under the hood” approach.
But hey, if you are under 10 people and need apps everywhere, it is a nice thing.
- Dedicated Android devs working on your Java/Kotlin/whatever Android app
- Dedicated iOS devs working on your Swift/Objective-C/whatever iOS app
- Dedicated web devs working on your JS/TS/whatever web app
- Dedicated BE devs working on your BE services, in 1-many languages that may be none of the above
But for startups, that’s not gonna happen, there’s gonna be wayyyy fewer devs and wayyyy less specialization. A lot of companies will be in that mode for many years, possibly indefinitely. In those situations, React Native can be a big win. I’ve been working the past 2 years at a relatively small startup, ~10 devs, that’s TypeScript everywhere. We’ve got 2 mobile apps (mobility space, a Rider and Driver app), both TypeScript/React Native/MobX. Rider is iOS/Android/web, Driver iOS/Android, very nice having 2 apps instead of 5. Then a web-only admin app in TS/React/MobX, and backend services in TS/Express. Same language everywhere, and similar mental model across all FEs, is a big productivity boon at our size.
There are not many examples of such code bases. Maybe numerical algebra libraries come close.
Reading through the comments it seems that providing (fairly basic by now) UI functionality on cross-platform basis has not matured to the point of providing a stable paradigm.
Given how many people and for how long have been banging on this problem it feels a bit strange.
Surely people can find better use for their time and energy than churning through half-baked frameworks?
One has to ride (and eventually) create trends to sell.
We should have all stayed on backbone or Prototype.js with that logic.
People look for alternatives because the status quo is awful (slow, verbose, footgunful).
You’re saying “who needs cars when we got horses? Cars break down all the time”
The UI problem is not new. People were already building clunky UI cars long ago. MFC was introduced by Microsoft in 1992.
Of course the emergence of the web platform and mobile/touch devices complicates the matter as you now have a proliferation of platforms to address (desktop native, desktop web, mobile native, mobile web) but my argument is that fundamental patterns on how to do this efficiently should have emerged by now - and I see exactly the opposite.
It would be nice to see some sort of convergence. Reinventing the wheel might be "fun" or gainful in a narrow sense but it certainly doesn't help with productivity.
"1990 CERN: A Joint proposal for a hypertext system is presented to the management. Mike Sendall buys a NeXT cube for evaluation, and gives it to Tim Berners-Lee. Tim's prototype implementation on NeXTStep is made in the space of a few months, thanks to the qualities of the NeXTStep software development system."
I don't understand this quote from Tanner. Aren't React hooks, like, the only way to tell a function React component (while inside of it) to re-render? And if you look at the code of, say, the useBaseQuery hook of tanstack-query, you will indeed find React's native hooks being used there [0].
0 - https://github.com/TanStack/query/blob/main/packages/react-q...
While of course React-query plugs into the React lifecycle, it's also kind of an escape hatch that plays nice with React.
Managing the fetch function calls, their state, their resolutions, and the cache, all probably happens outside of React, but then changes to any of the query state are reflected into the React lifecycle.
This probably lets him do something like using localstorage for storing cached query data, communicating between tabs, etc
At the end of the day, they approach the problem from two different directions, solve issues in two different ways, and end up with two different sets of challenges in terms of what's easy and what's hard in them.
I've definitely written React UIs that would be easier in Angular. But I've also crashed Angular performance through the floor trying to wire up a table display with Angular update hooks. Angular makes it easier to hide state-update dependencies in a way that causes really bad thrashing to reach steady state, which I've (anecdotally, generally) found harder to do in React because doing it in React involves writing a lot more code and a lot more cross-state dependencies.
Most of the footguns listed in this article are things you obviously shouldn't want to do because they're not React-y.
E.g. if you are dealing with forms a lot, I would strongly suggest using react-hook-form or formik.
That's neither required, nor being recommended by the wider community anymore.
> JSX
JSX on the other hand I feel like is something that is essential to React (yes, I know that some people disagree), and one of the few things it should provide/require, as it forms a cornerstone of it's UX. Getting things set up to understand JSX/TSX has been smoothed out a lot now, and hasn't been an issue in any greenfield project I have set up in the last 2-3 years.
It's a pretty major rant, without putting forward an alternative.
The only viable alternative for me personally is VueJS and that's not my cup of tea either.
I like React. It makes sense mostly.
Is React perfect? No.
Do I like React's recent transition to focus server side? No.
But the problems it addresses are tough to solve.
Show me a better solution and convince me its tangibly better than React.
I think React creates needless complexity. The software I write is complex by it's nature, I do not need the software I create my application within to exponentially increase that complexity. React does not just let one write code and create one's application, React dictates how the code is written, and if that does not fit with one's application structure you must change it. And React developers cannot wrap their heads around anything other than React's dictated way to write React, so... they are useless.
So, what do I use: nothing. I just write html/css with direct DOM access via js, very minimally. Dicking around with the web page is the least priority of the applications I write, and the freedom to create the application structure as the purpose of the application dictates is far more important to my clients. Plus, I do not write consumer click bait vehicle software, I write software for people to accomplish things, typically complex things of the nature an engineer, designer, or architect would use.
I've gotten to the point where I think frontend code should just be modeled as state machines from the start. I like XState but you can use reducers too if you like.
Back with components, it was trivial to compare old and new values and change the state based on that.
It reminds me of teachers who have been teaching so long that they don't understand what it's like to be new to the subject any more. It's called The Curse of Knowledge cognitive bias: https://en.wikipedia.org/wiki/Curse_of_knowledge
No affiliation, happy user for years.
I only advice against using a niche framework if you suspect the project is gonna be long-lived and managed by a medium to a large team, in that case pick the one of the big ones—React, Angular, Vue, or Svelte—which your teammates can agree with.
I despise what NPM has become, and how complex / time consuming the build pipeline of front end apps is.
It’s still not a mature framework yet but hot damn does it excel at just getting out of my way and letting me ship stuff.
I would recommend you to build a small project, maybe a Todo app in every framework you want to try, or maybe if you have a project, build a small part of it in each (I will pick the part that you think is the trickiest to build with React or the framework you are actually using).
Also I'll recommend to also check Qwik and Fresh(deno).
But I'm also interested in trying Solid.js and Vue, and for some types of projects I'd likely even go Astro+Svelte or Astro+React.
Hard to speak authoritatively on the matter though because over my career I've only done vanilla JS, jQuery, Backbone.js, React, and then Svelte, in that order, and each has felt like a leap forward in evolution
- Lit if I wanted to share components with other teams
- Marko if the site had lots of static content
- Qwik if speed was paramount
- Fresh too looks interesting
Not a single one of the many projects I’ve worked on in the last 10 years needed such a level of interactivity that it justified the trade offs of using react or any other frontend-heavy frameworks.
I’ve seen entire CRUD spas that would have been built in 20% the time if we didn’t have to build a graphql api, figure outs authentication and permissions, integrate that with a custom validation setup, integrate all of the above with the translations systems, coordinate deploys or do forward compatible migrations, etc, etc. so much energy (and money) wasted.
I'm glad others have found value in the evolution of react, but it always felt like watching a tragedy from the outside as the newest Abramov idea seeped through the ecosystem.
My own impression is that the core model of state and rerendering is actually quite nice and intuitive, though often explained a bit wrong. The part that makes it complex and confusing are things like callbacks, which can trigger lots of unnecessary rerendering and force quite some boilerplate if you want to avoid that. If you can remove all the stuff around trying to avoid rerendering unnecessarily, React would be a lot simpler.
I also think that people are too quick to use the wrong tools for managing state in React, e.g. Context to avoid a bit of prop drilling.
React enables v=f(s) by making DOM updates faster. v=f(s) was always a good idea, but before vDOM, replacing the HTML of the page on every little state change was too much for the browser.
- Now you describe your views as pure functions of their inputs and stop caring about them, React cares about them. You know that with the right s, the right v will follow.
- You need to care and manage your app's state carefully, yes, and everything goes in there. Fortunately, patterns and frameworks like Redux make it releatively straightforward to do this.
You can still make a mess, sure, and make mistakes, etc, of course. No silver bullet. But you can now deal with those two separately. If you start fetching data from your components directly you're back in jQuery hell with extra steps.
I may be wrong here, or it could be my age showing, but I feel like explicit UI systems like that might be more verbose, but I find them more accessible to dive into and less "magic".
I'm totally lost and baffled by everyone's enthusiasm for these increasingly arcane and complex abstractions. I suppose they are necessities that arise when you reach a scale that I have not yet encountered (I work on small to medium sized teams of a dozen or dozens rather than hundreds of programmers).
Alas, castles and fortresses have been built with messy goop, and the amount of goop-specific tools and goop slappers far outweigh the bricklayers. So I too slap goop.
I mean, they're absolutely necessary because the goop is full of insects. But so elegant!
I've been running a mobx-react setup for 7 years. It's been thru a few syntaxes but it behaves identically. Minimal rendering, observability, I find it the most intuitive state management pattern.
my forever setup is here:
I have also been able to consistently hire absolute greenhorns right out of tech bootcamps with zero formal computer science training and they were able to build features that made our company real money and push to production within the first two weeks. React can't be that bad.
Now that we threw out react-hook-forms (Remix does it all fine with default form APIs), Apollo (don't need their caching any more, so just sending plain GQL requests via fetch does the job), Redux (Context API is just fine), emotion (TailwindCSS is so so so so so much better)... our Remix codebase is basically pure HTML and Tailwind's css classes. It's a bliss.
> Humans have a cognitive bias: "what is focal is presumed causal".
> Political leaders know this. They like presenting good news themselves because they like to be "seen" as causal of good stuff, but they'll get a press secretary to deliver bad news. Movie directors know how to use this when framing their protagonists within the story.
> Unfortunately, the React team have lost themselves in this bias. They keep trying to make the most focal part of the system (components) also be the causal part. Please stop doing that! It is a mistake. Events are what's causal - they embody the user's intent.
> Just to be clear, I love React. What an utterly brilliant idea and great execution. I'm deeply grateful because, wow!, did it change things. It is just that I preferred React when it was only trying to be the V part of MVC. Everything since has been downhill.
[0]: https://day8.github.io/re-frame/FAQs/LoadOnMount/#why-this-d...
This line however "It is not obvious that your component re-renders on state updates." is kinda strange, maybe it's not obvious if you didn't read any documentation or tutorial?
also "You could build your own framework in an hour using reactive primitives [...]" is the same as when people say "just make your own sorting algoritm", yeah sure you can get the exact behaviour you want, but come on.
It's an additional layer on top of MobX that adds strong typing. I've been using it for an open source video annotation project and it's been amazing for keeping track of local state, cascading calculations of things.
Here's my "models" directory for it if you want a taste of how it works:
https://github.com/Rodeoclash/vodon-player/blob/main/player/...
Upgrading to newer versions is a pain and also finding well supported third party libraries. React is much easier to work with since you don't always need to reinvent the wheel for time consuming things.
Hooks and simple state management with Jotai are also much nicer to work with than RxJs. RxJs requires a strange mental model and a lot of verbose code and functions.
Angular is kinda like Java, more code for less features. Great if you don't wanna think, meh if you want something exciting and new.
Does immer count? :)
struct A { b : B }
impl Reducer<Action> for A {} impl Reducer<Action> for B {}
Now the reducer logic is spread out across the state. Sure, every sub-state now need to handle Action every time but with tools like ADT and pattern matching I don't think its as bad. I feel like this will be cumbersome, but the complexity should scale linearly.
(Submitted title was "React is a fractal of bad design")
I started out in these sort of frameworks doing Angular 1 in 2013. Did a lot more Angular 1 projects in those years, and really got to know the intricacies of the framework. Was ready to switch to Angular 2, but instead I ended up doing some native JS web components, a little React, then some Vue, and now some serious React.
I've got to say, I liked the little React a lot more than the serious React. All those useEffects everywhere don't make the code any more readable. There's layers upon layers upon layers of components and abstractions and layers in between. It comes across as less organised than my old Angular 1 or Vue code did, though that's probably also due to the size of the code.
Anyway, I'm not being held hostage by anyone. Next project I hope to be doing something in Svelte, but maybe I'll end up doing something completely different. Maybe some Kotlin? I still haven't used that.
On the other hand, other less experienced developers didn't like Elm so much because React allows you to write your app with fewer lines of code. The article from this discussion explains well that React (especially with hooks) hides complexity, which bites people later. At that time, it is perhaps too late to switch to something else.
Needless to say, I haven't been able to convince any other employer to use Elm, and then I see issues popping out all the time that would never happen with it. Such a waste, just because people like shiny toys and just follow what others around them are doing without thinking too much.
[1] https://elm-lang.org/ [2] https://redux.js.org/understanding/history-and-design/prior-...
For example, I recently wrote a react component that diffs it's new state against the previous state and then calls an imperative map API to bring it into alignment. Ideal, no. But I'm not going to wait for the compiler devs to do something perfect before I write this app.
But I think the criticism here is a bit sharper and more pointed than that. The author isn’t expecting Reach to do something for which it was never intended, I think. Instead, they’re saying that the abstractions (hooks in particular) that have evolved over time expose unhelpful interfaces that either conceals too much information, encourage poor patterns that lead to bugs, inefficiencies, etc.
In other words, the criticism isn’t of React’s explicit decision to offload responsibility outside the scope of outputting UI, but rather that it’s evolved to make handling of those responsibilities more challenging.
I think that’s a bit more serious than the former critics and worth at least considering. For my part, I’ve found little substantive advantage to hooks and do think they hide a lot of bugs by making implicit things that should probably be (and, once upon a time, were) more explicit.
Having to write optimized code usually makes dev ergonomics the first casualty.
Like the famous Haskell qsort. Every beginner sees a cute version that should never see the light of a production environment
Most of this article is a rant against the react hooks project, not React itself.
1. I’m not sure what they have in common with each other. What exactly is a React hook. Nearly every hook is its own thing, with its own purpose, use, etc. With the new “use” hook, even the original hooks rules don’t apply anymore.
2. Related to the above, every hook is an entirely new concept. Learning react you would think once you learn “hooks” you will be able to understand basically what they did. Much like once I learn “classes” or “functions” I can figure out what they are. But every hook is its own concept, with its own rules, and gotchas, etc. Sometimes I wonder if the reason they’re called hooks is to present them as a single Concept, otherwise it would be too obvious that React replaced a few concepts, state, and component lifecycle, with about 3-5 concepts in the library in the early versions, and many more now, with an infinite possibility of concepts through custom hooks.
3. No one in the React world seems to have a clear mental model of what hooks are. useEffect is the most egregious here, but the name (and the original React docs) indicated it was for side-effects. But then it’s also used for lifecycle management. Finally, it appears that now the React devs have started pushing the idea that it’s to keep “components in sync with an external system”. And useEffect is probably the most used hook outside useState.
To be fair, usually descriptions of concepts can change with time. But with useEffect it’s not just the description that’s changing. It’s the entire mental model, which makes it seem that the React devs themselves are not clear what useEffect is supposed to be.
Fundamentally, hooks seem to be a bunch of ad-hoc solutions that React devs use to solve specific problems they notice in the wild. But there doesn’t appear to be any fundamental consistency to what they really are.
The first example of UI frameworks is always the `counter`, but it's always the least realistic scenario you encounter. Almost every app involves retrieving state over the network, sharing state in multiple places in the app, and how this state is CRUDed.
The reality is that all state is very interconnected.
Ideally you want fine-grained reactivity for every rendered UI element, that ultimately reacts to the changes in a database in the cloud.
And every piece of state should ideally be persisted. Even things like dropdown menus and their state.
The simple solution to all this is to store all state/data in a single database on the client. Every time you render something from the database, a component should have its own "view model". And this view model should react to changes in the database.
This "view model" also shouldn't be hidden inside components. There should be one place where you can view all the view models throughout your code. And see the interconnectedness. In a visual way too.
Maybe we went off-track when we started to merge the view/model/controller in the same file. We create hierachies of views, and then they need to get their data from this view hierarhcy. But instead they should be getting their data from a central database in as few transformations as possible.
The mistake people make is trying to make components isolated and decoupled from the rest of the app as a principle. It sounds nice, in that when you work on a single component, you only have to worry about what props are being passed to it. What makes apps complex though is data transformations. Ideally you want data to be as close in shape to the underlying dataset as possible. Otherwise caching/memoizing becomes very difficult, and this is usually the cause of many performance issues.
I wonder how many of the issues people have with React are due to it not being built on a state management library - like Vue is, and Mercury was.
The rendering is whatever. Templates, JSX, it doesn't really matter. Mercury used hyperscript and we got by just fine. But state management is critical, and React seems to leave it completely up to you.
Vue added a hooks-like API. While I haven't used it in anger, I've toyed with it. And it sidesteps some of the weird React hooks caveats... because of Vue's reactivity system. Huh.
*With a brief interlude using the original Angular, which I did not understand then and still do not understand looking back from today.
> It’s just abstractly funny to watch the ecosystem of a UI renderer work so tirelessly to keep using it while avoiding every part of it.
I would call this concept noodle. Because when there's a lot of them you get back your tasty spaghetti. The whole reason for React was avoiding it whenever possible.
I use sometimes, but for the most part is overused feature.
I think thats a symptom of a problem with the front end community, people get too attached to the new thing and try to make it the standard instead of building something stable and concise.
Im tired to having to rewrite a code because one library that I had to upgrade decided to migrate to the "new thing"
And using it professionally for years now, there's still some cases I can't wrap my head around. And the mental model is just a bit "off". Like, the same function is ran multiple times, but with different behavior (like a useState only uses the parameter the first time the function is ran) which is very unclean.
It's not even orange for me. I changed the "topcolor" in my profile settings to d0c8b5 - a darker shade of the body background color. Now the only orange thing is the Y logo. Much easier on my eyes this way.
I’d love to know who started using it first, though.
Why the modern obsession with hiding the underlying state machine with callbacks? To prevent devs from seeing the bigger picture?
I'm lucky that I am an independent developer so I can choose to use Solid JS in my projects.
React has so many gotchas and they keep changing the 'best practices' I can't believe people still stick with it.
Does anyone have a source?
In game dev you run millions or even billions of computations 60 times a second. If running toTitleCase three times every key stroke is an example of a compounding performance problem in React then surely the problem must lie deeper.
POST/Redirect is beautiful. It’s fast. It’s simple. It’s low maintenance.
> What would framework-integrated fine-grained reactivity look like? Probably something like Solid.js
It would look like JavaFX which has had this exact approach since it launched over 10 years ago as well as a large library of observable operators and collections complete with delta events, the ability to define components with a "shadow DOM", with custom CSS properties, using both JSX-like widget-oriented markup and code, and a whole heap of other things the web community has since slowly rediscovered. Here's the high level observable operators API (there is a lower level one that lets you define custom operators):
https://openjfx.io/javadoc/19/javafx.base/javafx/beans/bindi...
And here's the author's Solid.js example in Kotlin with FX:
class Counter : Label() {
private val count = SimpleIntegerProperty(0)
init {
textProperty().bind(concat("Counter: ", count))
timer(period = 1000L) { runLater { count.value++ } }
}
}
You could also write that in many other languages like Clojure (with cljfx for FP fans), Python, Ruby, JavaScript, and of course Java. It would be less verbose if I used a library that better used Kotlin's features, but the goal here is that you can look up the APIs from the link above (there are a couple of implied static imports).So not much different, but it demonstrates how the text property of the label is bound to a dynamically computed string which is in turn bound to an observable number. When the timer fires, the count increases and the label is recomputed. Everything is done that way so layout computations, for example, won't run unless the size of the label changes. And that's it - no need for VDOMs or prop drilling or state memoization or any of these other performance hacks.
At some point you'll observe that this seems a lot like "reactive programming" as used on the server side, and then might want to explore a library like ReactFX which connects these two worlds together.
https://github.com/TomasMikula/ReactFX
There are some other nice features in this type of toolkit that the web community seems to be heading towards. I'd be willing to bet a lot that at some point they'll even reinvent inheritance under a new name, because being able to write code that's generic over component trees is really pretty useful. The hooks/functions model totally wrecks that and has led to this explosion of "design systems" (otherwise known as themes that bundle half a widget toolkit), none of which interoperate properly or can be coded against in an abstracted manner.
None of this is to say that FX is perfect or that React/SolidJS etc are the wrong tools to use. You can run FX apps in a browser using a form of server side rendering - check out https://www.jpro.one to see a fully crawlable website that's actually implemented using JavaFX on the server with no frontend/backend split existing at all. But it only works well if you don't have a fast and reliable server connection, plus a server with plenty of RAM and CPU. Alas browsers pull all sorts of mean tricks to keep people locked inside the HTML5 sandbox so JS frameworks aren't going anywhere, but it would be nice if that community spread its wings a bit and looked at prior art from outside their language. GUIs are old and the challenges involved in them aren't new, and from the outside it looks suspiciously like there is no real progress being made here, only wheel spinning.
we are all just primates staring at blinking lights and poking things
I need a web server to work by slapping together fifteen Java libraries from thirteen different code houses and writing an absolute Shoggoth of shim code to convert between their types and classes? Sure, whatever, datacenter storage is damn near free.
I need to put code on a client machine on the internet? You'd best pick one of these date libraries, because there's no way in hell we're justifying shipping moment and Joda down the wire.
It seems like the framework culture is driven by the search for a silver bullet that makes problems go away. But each solution to a problem always comes with its own set of problems, only these problems are initially unknown. So you trade a set of known problems for a set of unknown ones.
It is possible that these new problems are lesser problems, but this is hard to verify upfront, and the nature of being unknown makes it a lot harder to deal with them preemptively.
So anyway, you have your framework, you have used it for a while, and you have learned about the previously unknown problems that it causes. You could rejoice that you now have this knowledge, and therefore have a reasonable shot at working around the problems. But instead you ditch your imperfect framework and search for a new one, beginning the cycle anew.