"That's a lot of code to write for an automobile-incrementing counter"
In reality, you will never need to write an auto-incrementing counter :) React gives yous a mental framework, you draw a page based on the state in a declarative way. The clever abstraction you make, the less you write the code, so information technology'south a little bit pointless to compare it with an auto-incrementing counter application, in reality has no use case at all.
For anyone who wants a thorough agreement of how to remember about React hooks in the context of things similar setInterval, Dan Abramov wrote a peachy piece breaking it down in particular several years ago: https://overreacted.io/making-setinterval-declarative-with-r...
This mail service helped hooks "click" for me, and once information technology did, I've absolutely loved them and now thoroughly savour writing custom hooks that greatly simplify my code.
Honestly my promise (and I admit as a total-stack but leaning dorsum-end developer to exist biased against JS) is that the futurity is in things similar turbo-stream, stimulus reflex, phoenix liveview etc - or in things like all_futures (essentially an ActiveRecord wrapper effectually kredis) - that we movement towards building reactive-apps by firing off events from the back-end and figuring out how to subscribe to them on the front-end
the amount of disruptive boilerplate I've seen to keep updated and maintained when a JS framework is loading front-finish country by making API requests against a backend and then trying to figure out how to continue those in sync when we could only be firing off SSR HTML over the wire and/or very sparse events that FE components can subscribe to or emit for literally no gain in functionality is beyond me
even better, simply add reactive sprinkles over what you need reactive and do the balance with standard MVC/Residue patterns, if most of what you are using react for is glorified forms, you don't need react for that! user your reactive sprinkles of notification toasts, and conversation channels...
I'm not saying there are no use cases for a JS framework, and I have a few I like, just that the switch to rails api only/separate react app has in nigh every example I've seen added tons of complication without a articulate win
Imagine you have a Rails controller with a form template and y'all want to have a section of the form show or hide based on the setting of other course elements, plain without reloading. Can you practise it? Yes. Does Hotwire/Stimulus make this possible? Yes. Can information technology exist done in a overnice like shooting fish in a barrel to use way? Yes. If you stretch beyond what Hotwire/Stimulus can allow yous practise, do you take to completely switch over to the "frontend applied science" path of single page applications (React/Athwart/Vue/Svelte/etc)? Also yes. Are the primitives you utilise in Hotwire/Stimulus in any fashion continued to the ones you'd use if the use case got even a trivial more than complex? Admittedly not. Why not just have one set of primitives that work for all applications?
It's not similar having some frontend templating logic or reactive forms or whatever is going to actually be harder than merely doing information technology in Rail if you are familiar and comfy with both. If you lot aren't comfortable with both, then that's fine.
Those are very unlike applications and the trade-offs involved are completely different.
In the -common- example OP seems to me to have a valid bespeak.
For forms-over-data business applications, sure it'southward fine. Information technology's tradeoffs effectually the organization use cases, potential/realized functionality, and team.
But I think that serving to public users with server-driven MVC for an application that goes beyond a pure content app has immediate and obvious limits in terms of what can practically washed, and the more than you lot attempt to overcome those limits the more you simply rebuild what is already available in the SPA side of things.
It'due south also inherently monolithic, significant that if y'all desire or need to support a mobile/native app for your public-facing app, you'll at present need to develop a new "interface" (an API), when you should accept already done that to enable the web app in the offset place. Is it really worth skipping API/UI separation on day 1 when you know it's going to be needed on calendar week 2?
You might say, information technology's fine, we're going to just make API calls for the Javascript, just so you've got an inconsistent availability of the functionality, and the second y'all hand that to some other team to consume you will have wished yous had simply built out all of the needed functionality directly in the API anyway.
Almost every criticism of React that I've read, goes away when you drive information technology from Clojurescript. If you haven't had the pleasance I suggest you accept it out for a spin.
Example of a full blown React component in Clojurescript:
(defn counter [] (let [state (r/atom 0)] (fn [] [:div {:onClick #(swap! state inc)} "The count is: " @country])))
Reminds me how vanilla hibernate is unusable simply Grails'/Peachy's GORM (congenital on Hide) is admittedly fantastic.
I've been using React since around 2016 and when Hooks were introduced I played around with it but didn't similar it at all exactly because of the reasons mentioned in this commodity. Certain it reduced quite a scrap of boilerplate code that came with class based components and enabled amend code re-usability outside of class inheritance or mixins but the disadvantages were too big for me personally to really consider using Hooks in a "greenfield" setting.
In my current project I'chiliad using Vue with Limerick API which gave me the exact aforementioned "aha" moment the author of this article had with SolidJS. Vue + Composition API is way more similar to SolidJS in principle than React + Hooks.
Pure function components in React with MobX for state management rather than the hooks organisation has worked out quite well for me.
I do, however, proceed finding myself wondering about jumping to Vue and VueX instead.
Ask me in five years, I judge.
We've used React with Mobx in commercial apps for 5+ years at present. React has been skilful for us BUT Solid is so much cleaner (and leaner).
Porting most React code to Solid is pretty like shooting fish in a barrel - mostly involves deleting things that are no longer required (useCallback, useRef, etc) and moving prop access into the JSX to enable just those specific attributes to be updated when state changes.
It has come up to the point where I really begrudge going back to working in our React code. Unfortunately those apps will still be around for a long time - but we won't be using React for green-fields projects.
Equally somebody who's quite enjoyed mobx I would encourage you to write upwardly your experiences.
I would promise that while -me- reading any such blog post is almost certainly going to exist irrelevant, it might pay off enough in recruiting/marketing/pure nerdery to exist worth the effort to write it upward.
Slightly OT: I'm ever amused coming to discussions like this 1, where people are (basically) complaining nigh the Virtual DOM and its implications. Information technology'due south bad for performance at scale, updates aren't minimal. And other stuff: SFC are hard to wrap your head effectually, I don't desire to write explicitly reactive code and so on. Some framework solves this by looking (somewhat) similar React but in the end doing something entirely different.
May I interest you lot in Athwart? It certainly isn't absurd and I actually practise hate it. But especially since the AoT compiler has been implemented, operation is quite good. In that location's templates, which some folks seem to love. Angular keeps in-memory references to all dynamic elements in a template and so they can be updated with high efficiency. It has class components. It has a lifecycle method that is called OnInit. So maybe requite it a whirl.
I've been using Angular in production for 5+ years. There was a yr where things were confusing, country updating all over the place, and general frustration. Simply once I grokked pure components, and embraced "data down, actions up", information technology all clicked and just made sense [0]. I find React obtuse in comparison.
Angular front-finish, Nestjs backend has fast go my stack of choice. It profoundly minimises context switching by having such similar paradigms across frontend and backend.
[0] - weblog series I wrote detailing Athwart best practices that I learnt along the way: https://link.medium.com/ncYgWgnK2nb
The whole "I hate angular" is a scrap sometime at this point. The latest versions are really quite elementary/powerful. We deed like it's nevertheless 2015 and we're jumping from angularjs 1.x to React. The bound was nice, yet turns out production-grade technology in React was non so nice.
I don't like the separation between template and code, I don't similar the programmer experience (slow and ofttimes malfunctioning VS Code extensions and slow builds, bad in-browser debug helpers), I don't similar how creating "ad-hoc" components is basically impossible.
I remember Zone.js is insane.
I know Angular very well. That'southward why I'm confident I can create high-performance applications using Angular. I firmly believe Angular has far too many pitfalls for inexperienced developers.
So yeah, I hate Angular.
If yous can't hate on your major dependencies confidently and at length, you probably haven't used them long plenty yet.
I generally spend much of my solar day writing perl. It absolutely works for me, but every time I encounter somebody who wants to -assail- perl I find myself disappointed by how short their list of reasons to hate it is compared to my own.
(ane of the most complicated JS codebases I work with on a regular footing is in angular, and the learning bend is a fucking cliff but yeah, in one case yous get to the top, I hold with everything y'all've said almost it)
`Athwart Language Service` is the only domain specific extension I've ever needed and its never been an issue. The template separation, as well as (s)css, I like organizationally compared to the chaos yous end upwardly in with big jsx-styled applications.
I find Solid.js a "ameliorate" React as well. In a new project that needs to be used past a lot of team-members, however, I still chose React.
Why? Because of the ecosystem! Exercise I demand accessible, headless components? Apply React-aria from Adobe! Do I demand state management? At that place are many established ones, I simply need to follow their best practices. Everything supports React, every hire speaks React, and it works, non like "just works", merely "... works" and, disappointing to the engineer inside me, this is non something I can trade in big projects.
Equally with any new JS framework technology, information technology will feel great until its flaws, warts, deficiencies and limitations are inevitably discovered equally complexity rises, and which are and so addressed in the adjacent JS framework.
Great bulk of my projects are data dashboards and I struggled with React for some time because of its top-down model - information technology can hinder functioning really badly. If one of your points on scatterplot should be marked, you need to carefully laissez passer this prop through few memoization layers, so whatsoever other points won't try to re-return.
I've been on this quest for a long time, considering I similar React model. So I had fun with putting observables in my app (kefir and karet from calm-js and my ain thing with xstream), I tried custom selectors with redux and all 'like-redux-but-simpler' libraries, I besides tried recoil. These solutions tin piece of work and worked for my apps, just it felt like I was fighting against React.
Solid was squeamish. Information technology provided necessary tools to write interactive information visualisations with ease and in performant mode. It has quirks but they are manageable - my team besides learned and contributed to projects in Solid.
First, the concept of "component functions" that are more like factories. It is non groundbreaking (reagent had this idea long ago) but is quirky. Thankfully, half hour with Solid playground and everybody can encounter what code is generated and how it works nether the hood. It is really predictable but also tangible - you can play with just part of your app in playground if something is unclear.
Second quirk is props object. I empathise the trade-off but it trips users (me included) that you tin't but care for it every bit regular object. Sadly, only solution for this is lint rule - yuck. Just information technology is much simpler dominion than hook rules - but don't destructure props.
In the stop, Solid is dandy tool for "web apps". Retrieve virtually dashboards or diagram editors. Cheap components, fine grained reactivity, focused updates yield great performance results without jumping through hoops.
Tin anyone explain the point of the virtual DOM and why it's not a source of huge performance issues? What I mean as soon as you retain a reference to a DOM chemical element, it'southward lifetime becomes managed past the JavaScript gc - let'due south say you build a paginated gallery app in pure HTML and an spa - in the kickoff case, the browser knows that as soon as y'all navigate away from the page, all those prototype thumbnails are gratuitous existent manor, at the latter instance it first needs to look for the spa to release references to the underlying html objects, then the gc needs to run, at which point information technology tin become rid of it.
The reason for the virtual DOM: in react, the unabridged world is a function that gets rerun on every render. The whole point is to exist able to define some state and and then render the whole earth in accordance with that new state. When react was conceived, Dom updates were very slow and could bottleneck the application.
Knowing that your entire UI is running within a role that gets re-executed with every render, gives a tremendous amount of safety and predictability to your awarding and makes testing a breeze. But you tin can't actually rerender the whole world every time because functioning, so instead React relies on a JavaScript object to concur a representation of the UI, then surgically updates only the pieces that need updating. This was React'south big matter.
The reason people want to move away from virtual dom is because browsers have gotten faster and now the Dom updates aren't the biggest source of overhead.
I tried to do a pokedex in react, you have to use a virtual list, considering react/virtual dom is too deadening, doing any operation on a plain list with 1k element, similar filtering lead to multiples seconds freeze.
This as well pb to a lot of issues, similar non being able to ctrl+f text being out of screen in a virtual list.
I don't understand your issues hither. I built a customs app for a hockey league that manages around 120,000 players in the DB. I practise tons of loading, sorting and various algorithms on the data. I've never in one case had React exist my bottleneck.
Rendering a page server-side and delivering it to users is about as inefficient a process as y'all tin can get unless you accept massive resource dedicated to an optimization almost no ane needs anymore. The virtual DOM is extremely efficient, it just needs more memory and CPU cycles on the customer which are resources readily bachelor. Browsers are very good at managing this in 2022.
Btw, your code in that article is completely irrelevant... I would not be showing people that article in 2022.
I bet you lot don't brandish the 120k players at one time on the forepart, you lot use some sort of virtualised component (like ag-filigree) thats put in the DOM only what is displayed on screen, and keep the whole set in memory.
Information technology crusade an issue: now the search in document browser characteristic will not work properly.
This is acceptable the usecase you are describing(due to the huge dataset), merely a lot of interfaces use such virtual list, and it's an PITA for the user.
Take Azure DevOps for example: In a lot of place, y'all can't ctrl+f a projection outside the screen, even if it exist, you take to scroll to it.
> Rendering a folio server-side [...]
Nobody talked about server side rendering there.
> The virtual DOM is extremely efficient
Did you lot read the article I linked ?
The virtual DOM is non "extremely efficient" information technology's only skillful at removing uneeded DOM modifications. Not doing these uneeded modifications in the start identify is faster.
I have hit a betoken where I've moved my browser from running locally on my laptop to running on a hetzner dedicated server over VNC because it performs ridiculously better so "readily available" is obviously an unfortunately variable claim.
I would note nevertheless that my laptop is not entirely recent and I'thousand using firefox and my big pain point has been React Native Spider web apps like web twitter. So yous're probable still by and large correct, and the question inevitably becomes "how much more often than not is plenty for whatsoever given application".
https://tigervnc.org
Does some impressive compression tricks that results in it being remarkably snappy.
You may prefer to run Xvnc directly rather than apply the wrapper script, depends how you want to set everything up.
I will exist honest here that my setup is non properly automated yet considering it'southward inside a jail on a FreeBSD install and the underlying box gets good plenty uptime that my current half-assed approach hasn't withal annoyed me into finishing it.
There weren't any interesting gotchas though.
Great article. The fact that Athwart, the framework built by the visitor who too builds the earth's well-nigh popular browser, does not have a virtual DOM, is very telling.
I wouldn't acclaim angular for the functioning either.
Building apps on it show consistent subpar functioning.
generally speaking, Angular handles dom manipulation amend than React and Vue. Angular has managed to simplify its enterprise/product applicability and performance is a offset-order characteristic that's hard to f up. React -- you can f performance upward before you're washed writing your outset component.
Information technology'south really a terrible commodity that has no relevance in 2022, and it is even misleading for 2018 standards.
I ran a profiling tool. I searched "zz" then deleted these.
Deleting information technology caused a 120ms UI freeze (and I notice it :p):
Given I had slightly more entries (a hundred more than) and that I had manner more node per entry, information technology led me with way worse performance.
Instead of a evidently list I take a little summary card per pokemon (which is why I have more than node per entry).
The naive implementation in Vue run flawlessly(sadly no preview):
https://github.com/Kuinox/kuinox_pokedex/
Note that the react implementation exercise weird affair considering I tried to get effectually the outcome without success.
Regarding the example under "Reactivity, not lifecycle hooks":
Does the <Counter /> component reference the same outer "count"? So is "count" hither global or local to the component? In other words, what is the scope of "count"? Does it change based on where information technology is placed? If I create multiple <Counter /> components, do they all reference the same "count" or is information technology different for each component?
Sorry this question might seem naive if you are experienced in SolidJS. I haven't given SolidJS a shot yet (though it is on my list of things to check out).
I call up the count variable is quasi an Rx subject, information technology has identity and whatsoever code using information technology is keeping a hard reference on information technology. It would probably be GC'd if nobody referenced it. In my understanding, yes, multiple components would use the same case of count.
Yeah this is correct. The trick to this is that the subscriptions happen in our JSX and hooks. And really is just a nested tree of `createEffects` if one ever re-evaluates or is disposed it releases its kid computations. So while the lifecycle isn't tied to components it is still hierarchically structured. Ie.. places where logic tin can co-operative becomes the owning telescopic, like conditionals or loops. Then Signals like count don't really matter where they alive and will alive equally long as in scope or referenced, the rendering still largely defines how long things are around.
I've spent the past month kind of rewriting parts of Solid in an attempt to better understand information technology, and coming from React the way Solid works is just then much more beautiful, it feels liberating.
There'due south no rules of hooks, no dependencies arrays, no stale closures, no wildly unlike resulting performance depending on where exactly yous put your components boundaries, no VDOM at all, no props diffing, when I change the country respective to an aspect or property that only gets updated immediately, the way deep DOM nodes structures are created is sooo much more efficient... it's amazing!
Equally part of my annual routine, I'm exploring the "latest and greatest" JavaScript UI library. Solid.js'due south performance seemed compelling. xv minutes into documentation and this is what I encountered. Can y'all gauge which one of the ChildComponent* updates when the text input on the parent component is updated, and the props passed to the child?
The answer is three, 4, 5, six. My takeaway is this: in that location are multiple ways of doing information technology right, but likewise a handful of gotchas. The but way to be safe is to go along the mental model of these partitions while you develop, test, debug, and code review. Equally a code reviewer, yous can easily have the wrong code. For now, I remain skeptical of Solid.js as solving the complexity woes of Reactive programming. I'm not sure React.js is amend.
Or Vue either to be off-white. Similar rules in the Vue'due south setup function. It's how reactivity works in JavaScript. Basically don't destructure or access values out of of primitives or JSX. That'south basically the gotcha.
Unfortunately it'southward the cost y'all pay for portability thus far. You can build your own language effectually this like Graceful but then composability is limited (need to rely on other mechanisms). You can brand the updates coarser grained like React only then you demand a dissimilar mechanism(like VDOM diffing) to apply updates granularly. I imagine this situation improves in the futurity but we haven't gotten there yet.
Out of involvement, what language features exercise you see JavaScript needing to support these kinds of fine-grained reactive updates, and to let destructuring?
I'd assume something like es6 proxies for archaic values would be needed, merely that, nor congenital-in reactive primitives, are being discussed currently every bit far as I know.
Personally, I'd love to see reactive `[].map` equivalents (no need to employ <For> components), only that's possible today with a reactive wrapper or (god forestall) patching the prototype.
Grade components are fine for the simplest examples, but the moment they offset increasing in complexity, they get a bit of a mess. Sharing functionality across multiple components becomes tricky with course components (with the only real choice being HoCs / return props). You necessarily have to spread logic across different lifecycle methods.
Hooks allow you to package code together by functionality, and consequently permit you to easily excerpt and share said functionality in a very composable style.
This is my go to for visualizing the difference: https://i.imgur.com/e9K8vfz.gif
> Hooks permit yous to bundle code together by functionality, and consequently let you to easily extract and share said functionality in a very composable way.
You're using React. The mechanism that enables code reusability is through composing components.
There'south nothing wrong with class components even for the most complex logic. The simply downside is the customs has moved on and by and large adopted hooks and functional components.
> The mechanism that enables code reusability is through composing components
Although you'd accept to somehow ignore the fact that yous'd end up with an even bigger mess if you desire these intermediate functionality steps to collaborate with the parent component in a non-little fashion, ..
Needless to say, I have written such return-prop and "renderless" components in the past, and I come across very picayune upside compared to hooks.
Thats interesting. Then in your 2nd instance, am I right in proverb the variables 'apple' and 'slicedApple' are react JSX that you lot are ultimatly passing through to <DinnerPlate/> to return on the screen? If so, yes, that is fairly intuitive.
'apple tree' and 'slicedApple' would more likely be strings / objects / arrays in the real globe. Maybe this still woefully contrived version is clearer?
I don't retrieve deal with more braces right at present to bring the culling into existence unfortunately
Thanks for the viz, haven't done React in a while and so it's interesting to see how things have improved. The new image seems alot meliorate modularized and the logical structure seems easier to follow, combined with it taking advantage of newer JS features.
I think in the class globe this is ordinarily washed past writing a service and injecting it on the constructor of the parent class. Since, React doesn't have DI built-in, it becomes problematic with the injection. hooks are essentially classes imo.
How does it become problematic? Yous merely pass in dependencies every bit arguments to functions or components.
It's certainly a leak. That setInterval is going to be holding the closure context alive which volition reference the component in many frameworks.
The setInterval will too continue firing causing, wasting CPU and battery.
It's difficult to accept whatsoever examples hither seriously without showing proper cleanup that would pass lawmaking review.
Skilful to see other people spotted that, I noticed it immediately and had a "in that location's a bug! a bug!" alarm bell ringing in my head throughout the rest of the article. I may accept some sort of setInterval related PTSD.
The upshot is more about non understanding how React works and how to employ hooks. The setInterval example is hands solved. No, you can't only half-assedly guess your way to a right solution.
Also, composing asynchronous behavior with useEffect is also non a good idea. Don't abuse useEffect as an Event Handler (also much). Remember nearly using Redux (+ thunks/saga) or something similar.
This looks a lot like my current favorite state framework (which yes is done by Facebook people), Recoil - https://recoiljs.org/
Your naming still reminds me of the RxJS and full general reactive programming prototype I've ever pined after... some combination of the two would exist my UI state management holy grail.
Many devs take succumbed to the siren song of event sourcing. And many code bases have sank on those rocky shores.
I'g surprised to encounter so many negative opinions nigh React. Surely, I can't exist the only 1 that truly likes React and finds myself beingness extremely productive and making impressive apps with it.
You're definitely not the but i. Just I find it refreshing to hear some people voicing many of the complaints I've had about React for years. Up until very recently, criticizing react seemed to be almost unheard of.
Accept you tried solid/vue? If so, consider adding your perspective of what react does better.
I haven't used Vue in a really long time. Last fourth dimension I used information technology, Evan You had just shipped Vue 2.0. Using Vue was honestly a fantastic experience, and a great stepping stone to get off of Angular 1.x. I actually enjoyed its arroyo to data binding and unmarried file components where the styling, functional logic and templating was all contained in a single file.
At the time the promise of React was very far-fetched: using JavaScript generate your HTML markup. I actually was really adamant to use React and held off on it for a long time. However, once I gave it a fair shot, I was blown away by how intuitive it felt to use. I think the mental models it champions really helped bulldoze its adoption.
While information technology was a pleasure to apply, I was always wondering about other frameworks. Just where React really locked me in was in its support. `create-react-app` was an incredible achievement, tbh. It made information technology so easy to first using React and have all of the bells and whistles out of the box without ejecting. Then, once y'all exercise squirt, all you have to practise is alter your Webpack configuration and you can get all of the additional stuff you want. The community as well made incredible packages, similar Downshift and Emotion, which farther fabricated React an attractive tool.
Over the years the React team has kept innovating it. Hooks fabricated it so much easier to just write functional components, which has always been a core tenet of React (admittedly, Solid.js was using hooks before React). More recently, React added the concept of SSR/hydration to its framework. Initially a lot of people made fun of it considering it was like we went back to HTML generation on the server, simply and then developers realized that you become the all-time of both worlds: immediate markup from the server with the reactivity and snappiness of a single-page application.
Because of SSR we now have innovative frameworks similar Adjacent.js and Remix. I know Vue iii/Nuxt.js exist at present, and I know Solid.js exists at present, simply at present that I've started using Remix I'm trapped in React land again (and honestly, couldn't care less). Remix is so freaking good and information technology'south such a freaking improvement from when I did SSR in 2019 that it's hard to come across myself using another framework.
This is kind of a bad reply, only at least I can show you why I'm locked into React I haven't tried whatever other framework (I too genuinely enjoy using React).
There are some things I don't enjoy about React. I don't enjoy how prevalent Redux is when developers remember well-nigh global land. I too don't retrieve contexts are a expert enough solution (having a adept reactive model would have definitely helped here). At that place are other things I don't like about React: I don't similar how often it calls functions; it's extremely wasteful in big applications if you lot're non conscientious. And the semantics of `useEffect` are really murky for newcomers (and fifty-fifty sometimes for experienced developers).
If there is something similar a Remix equivalent for Solid.js I'll requite Solid.js a shot. But right now I'm in dear with Remix. Maybe I tin can use Remix with Solid.js? I'll take a look.
I dearest solidjs, but the similarities to React are the hardest part for me. The semantics are so similar, just the mechanics are the polar opposite.
In react, everything is a role and all your code runs on every render unless you specifically tell it not to. This actually encourages a certain manner of writing lawmaking and provides a lot of guarantees almost prophylactic and telescopic.
Solid is literally the polar reverse, your lawmaking runs once, and only the parts that you lot specifically make reactive are reactive. This allows for much finer-grained updates and performance.
The mental models are so different because they are optimized for different things. React allows for developer sanity (cue all the people who worked on i lousy react app telling me that information technology doesn't) and Solid optimizes for speed and simplicity.
Solid is very well designed though. Ane of the features I loved is that Ryan specifically congenital it to work equally possible to vanilla html/js so you can re-create old stack overflow answers.
I had the same problem: spending time trying to figure out why something didn't paint. You also can't use restructuring the way yous might expect. Information technology'southward a absurd library, though. I remember yous just need to go on a different fix of nuances in mind when using information technology.
Agreed, and typescript is essential. I'm withal new enough to the patterns used in solid that I tin't always tell whether a prop is a value or a signal, just with TS it's footling.
and Solid JS runs very shut native JS speed! Whatsoever i making a Reactive Native Connector for solidjs? Vue Native was already using that connector. with that, Solid JS volition exist ultimate isomorphic lib to utilise.
I wonder if there's an immediate mode framework for Js, in the vein of IMGUI for C. If people are wondering what that is, information technology'south basically this:
role renderGui() { label('howdy') if(button('click me')) { console.log('I accept been clicked') } }
This seems like a huge step back from declarative UIs, any reason why yous would say it'southward preferable?
Performance, for one. This method can easily avoid allocating an object for every div (since it turns into a method call, non something that needs to return an object), compared to React's render() method.
Another scenario outlined in the article of rendering a row of buttons, each with it's ain click handler, that needs to allocate a lambda for each push every render. Alternatively, using map() and filter() also allocates lambdas and temporary arrays.
All this can be replaced with a simple for loop similar:
for (item of items) { if(!item.isClickable) keep; if(button(item.proper name)){ panel.log(item.name) } }
Readibility-wise, it'south sort of an acquired taste, I'g not saying information technology looks better than JSX (merely it'southward a hell of a lot readable than React.createElement, so some syntactic sugar might exist put on top of it).
I suspect that the nature of the DOM ways that existence able to practise that in the get-go place would really require a virtual DOM w/diffing assuming y'all're targeting browsers.
However that'due south probably obvious, so: Assuming you're considering greenfield / blueish sky thinking hither, it's worth noting that v8 has had so much money and engineering hours sunk into information technology that the react-ish pseudocode probably doesn't brand near every bit many allocations as a naive reading of the code might expect.
(a good friend of mine was very surprised to discover that v8's JIT is expert plenty that naive javascript code was basically competitive with FFI-ing out to C++ just because the node FFI layer introduced sufficient overhead that the JIT managed to catch up ... I am not a compiler wonk so delight don't accept this equally a remotely skillful pronouncement but "it is, in fact, quite hard to overestimate v8 these days" seems to be a solid heuristic)
>the react-ish pseudocode probably doesn't make nearly every bit many allocations as a naive reading of the code might await.
Who knows, if V8 manages information technology to turn it into a for-loop? I don't, only afterwards a quick googling, as of 2018, it certainly didn't: https://github.com/dg92/Functioning-Analysis-JS
The trouble with JS is that the execution model is so nebulous, that functioning communication basically boils downward to - trust in Google.
Everyone goes on about operation but unless you are doing something extremely complicated or you have fucked stuff up in an extremely bad way, the actual part of React apps which is rendering to vdom and diffing to dom, in my quite long experience with it, is very rarely a trouble, and not enough to warrant a stateful imperative approach.
i think an immediate mode UI library would make sense if y'all desire to render to a canvass or a similar "backend". mayhap for things like games, or some interactive graphic things
but if yous desire to render to the DOM —and you lot want to use the DOM if you want to accept decent accessibility, or not accept to reimplement all the complex user interactions that the browsers take care of— then i call up an immediate mode framework might have a bang-up impedance mismatch with the DOM, every bit the latter is a retained fashion GUI model
Ane of the most compelling things about Solid.js is that it integrates some of React'south almost important (IMO, probably aside from the central idea of UI every bit a part of state) ideas for writing applications, Suspense, ErrorBoundary, useTransition.
Vue hooks avert the closure/scoping issue mentioned in the physician. Very similar conceptually, only I notice Vue's implementation a fleck nicer to employ
Took me 30 minutes to get up and running in Vue. Week 4 of this chore and I still can't unfuck myself with React.
I'm missing some toes from the quondam react lifecycle methods. The vanilla hooks were easy to utilise, reason about, and robust against misuse in a mode the lifecycle methods weren't.
I could run into custom hooks existence more than unsafe and difficult, only Higher-Social club Components are besides.
I always wonder why all JavaScript customer-side frameworks have such singled-out design.
No other dev surroundings for building GUIs has react-like components.
What'due south so special most the web that nosotros go along creating frustrating frontend frameworks for?
I personally love the front finish frameworks, and I don't find them frustrating at all. Knockout was a workhorse until angular came along. And so vuejs. And at present I use sveltekit for pretty much any web app.
The frameworks are popular because y'all can build things incredibly chop-chop one time y'all know the ins and outs of your framework of choice. The component-style pattern, the endpoint design, so much is just driven by the needs of spider web-based development and the framework creator'southward preferred way of abstracting abroad some of the challenges.
The browser was intended to render documents, not applications.
In particular, HTML has a tree construction, which means that things that are semantically related on the page and update together are frequently miles away from each other in the tree.
And the page in the browser is part HTML, function CSS, function Javascript. Frameworks try to let the programmer work in JS only and generate the rest.
And finally, much of the awarding'southward state is often kept in a backend, and access to it a asynchronous.
I think that's why Web evolution is and so distinct from other UIs.
One reason is probably that creating UIs programmatically was historically very cumbersome in JavaScript due to various issues that are no longer relevant. That means everything had to be HTML-based hybrids of some sort.
Considering at that place are a lot many js devs than others. Hence js ecosystem is significantly larger.
Later years of using Knockout and Athwart/RxJS, I'm not at all convinced that adding Observables to React is going to lead anywhere interesting.
This is the same code in Graceful.js
# Counter.graceful
<script> permit count= 0
setInterval(() => { count += ane }, 1000)
</script>
<div>The count is: {count}</div>
Probably the equivalent would exist a custom store, something like this:
<script> import { writable } from "svelte/shop"; function autoCounter(interval, initialValue = 0) { permit { subscribe, update } = writable(initialValue); setInterval(() => update((north) => due north + 1), interval); return { subscribe } } let counter = autoCounter(chiliad); </script> <div>The count is: {$counter}</div>
Yep. Looks sort of like the Solid case in the article. It's basically my auto-response to Graceful syntax. Once y'all practice annihilation in Svelte information technology is more than or less the same thing.
But dissimilar priorities. In Solid yous tin take that code as is in the component and hoist it out to a function above and presto.. store. It's still thing everywhere. Same patterns, same usage, same building blocks. No new APIs, no new syntax.
It is nice when first learning not to worry about Svelte Stores and apply the convenient syntax. It is also nice to acquire something once and use information technology everywhere.
Knockout.js was/is wonderful, I'm not sure why information technology never took off the way angular or react did. I practise appreciate jsx though and so I'll be looking into Solid.
As far every bit I could tell, around that time (and fifty-fifty now to some extent) the amount of activity on StackOverflow is used to measure out the popularity of a project.
Angular had a "made by google" kind of logo on its website, indicating to many people that it's of high quality and worth adopting.
Just Angular was also so convoluted and had so many bug that so many people kept running into random problems all the time and had to enquire questions about them on SO. This signals (incorrectly) that Athwart is popular, driving more than people to believe information technology's worthwhile to adopt it.
Knockout had neither. Information technology was not sponsored by a corporation. And information technology was so adept that you hardly ever meet random bug.
Ultimately it was eclipsed by React and Typescript because lack of type checking for the html templates means it'due south hard to scale it volition to large projects.
The bug with knockout were:
very hacky syntax embedded into html. Sometimes you lot had to fifty-fifty employ some kind of comment notation considering there was no entry point into the html to add data properties or any it had.
it was slow.
the observables weren't variables y'all could utilise similar plain JavaScript variables
it has the same problem as React - state-based algorithms are non very good ways to solve problems (if (showDialog && !open && ranOnce). You have to keep creating more variables to stand for more states instead of using normal programming language concepts, and then all of the observables ping around and become complicated.
It kinda is, but it'due south more than than just JSX. Solid was basically born out of Knockout and is in many ways a continuation of Knockout, but it has some relatively significant changes and additions to brand this approach more than viable, specially for large long standing projects. JSX is more of a quality of life thing, you lot don't even accept to use it, Solid'southward runtime exists completely separately of JSX and tin can piece of work bang-up without it or fifty-fifty potentially be integrated with other templating languages.
This is really interesting. I'chiliad happy the author covered the effects side of things considering this is where I've had some challenges with non-footling React apps. Sometimes effects can exist very complicated and result in React getting stuck in an infinite loop.
Before you say information technology'southward because I'chiliad "doing it incorrect", Material UI's website had this problem for quite a long time. That issue required doing manual refreshes to not trigger the infinite loops (something you would but see in the debugger). This problem in reactivity is a event in React that even the best devs can struggle with. My solution was simple... employ useEffect less. Depend less on reactivity.
The bottom line for me is that I experience like I can achieve annihilation in React, just the devil is in the details. There are and then many scenarios that I would need to vet with Solid.js, simply if it works better at managing a complex app's reactivity, it could be very compelling.
I am fundamentally skeptical of anything that needs a runtime for anything other than security and profiling.
I am extra skeptical of whatever framework that needs 50mb memory baseline.
I am triple skeptical of anything that uses brand-new packages and components like legos.
*Iterations on React are welcome.*
Well, you lot can be skeptical, and the enterprise front-end engineers are going to go right on using that stuff because it scales to large codebase.
Yes, right up until said startups and enterprises ane. cannot afford the outrageous deject expense or 2. Need to scale to low-power devices (such as wearables) and to customers who are security conscious
Don't worry, they're doing fine. Anyway, we were talking nearly React, to which none of those objections apply.
What feels like complete insanity when it comes to React is that it needs compilation to piece of work:
render() { return <div>The count is: {this.state.count}</div>; }
This is not Javascript and it volition need to exist compiled into Javascript before it gets executed.
Only you lot can do the same in Javascript:
render() { render `<div>The count is: ${this.state.count}</div>`; }
Using regular Javascript makes my life a 1000 times easier than having to go through a compiler to make things work in the browser.
This is another area where Solid has an advantage over React. With React yous could utilise Hyperscript functions so the above JSX would be
React.createElement('div', zilch, `The count is: {this.land.count}`).
With Solid yous get the pick, you could use JSX, Hyperscript functions or template literals like in your case. Solid does recommend using JSX because there are some tradeoffs to using template literals without compilation, but it nonetheless maintains most all of its qualities AFAIK and in the big framework benchmark Solid with template literals is the fastest template literals implementation.
With Solid you don't even accept to utilise any templating languages, you can have care of rendering yourself using the tools that the framework gives you. Solid at its core is more of a capable land management library similar to MobX just designed to be used as the just reactivity engine different MobX which is ordinarily used on top of React.
Using template literals to represent html is a security effect. If the state comes from the user, they tin can add script tags into the html. People effort to solve this with tagged templates, but so if you lot forget the tag, you have a security issue again. Lit checks for this, simply the fact that it has to check means it is less secure than not using tagged templates. There are libraries on github for creating sql using tagged templates which have the same security issue. The problem is that if your part works with both tagged templates and plain strings, when you forget to add together the tag, you will never know.
If the state comes from the user, they tin add script tags into the html
How is that unlike with React?
And how is information technology a problem? A rendering engine would set the html of some element to the html I call back?
Doesn't that brand an hard life for the linter that now has to decide which template string represents a (complete) chemical element and which is just text/whatever? I prefer the outset solution because it's much simpler to parse
Did anybody use Observable Hooks however? https://observable-hooks.js.org/
This seems to exist quite a expert way to compute and use complex country to a component. In my opinion better than useReducer().
Merely to be honest, for about components useState() and useEffect() are totally plenty. And if you practise something wrong like in the counter example, you see it right away.
Isn't this only the Vue composition API dressed upwardly to look like React? I haven't done frontend in a minute, then apologies if this is ignorant.
Mostly except in that location is no VDOM, the reactivity applies right downward to the DOM binding. And it predates Hooks and Vue's Composition API.
> That's a lot of code to write for an auto-incrementing counter.
Is information technology though?
I hateful I happily write more than code for a single-folio Vue component for something like this.
Terseness is non ever a virtue.
> Terseness is not always a virtue.
This is a subjective thing, right? Personally, I detest boilerplate: either it'southward a lark considering it'southward boring and superfluous, or worse it's long and it's wrong. Regardless, it adds to the cognitive load when maintaining code.
Yeah, definitely, hence the "not always" in this instance.
There are several terse syntaxes I actually similar. I'm but non convinced it'south a virtue in this context.
The vue lawmaking for this is pretty terse anyhow to exist honest. A single variable in data, a call to setInterval in the created hook and a few lines of html with template formatting. It's extremely clear what'south going on besides.
I tried several React alternatives.
At this phase, size of community is a really important factor, overriding many other factors.
It's just incredibly important for there to be tools back up, questions answered on stack overflow and a customs of people developing related software.
At this stage there's but actually VueJS, Angular and maybe one or 2 others with community big enough to justify irresolute.
Instead of vDOM, solid.js uses <template> - existent DOM elements + cloneNode().
And that'south doubtful decision. Each alive DOM element is about 100-200 bytes in memory.
While in React (PReact, Mithril) this JSX expression:
<div>a</div>
is this:
["div",{},["a"]]
5 or so times less.
In other words: needs to be tested on large DOM structures.
That's only a component template though. When yous produce big DOM copse, y'all unremarkably do so by rendering your components a lot of times, not by having a lot of different components
I merely dove back into react after a while in vue and deep in some backend systems.
I dear the new ergonomics (hooks, useEffect, redux tools) but I definitely hitting the verbal issue OP mentions about immediately.
I don't feel that the solution react provides is too out there, just agree information technology could be amend. The react ecosystem still makes it worth the i or two "could be betters" for me.
Y'all may need to remember about how you lot implement asynchronous side effects. Declaring them with useEffect quickly gets annoying. Look for things like thunks or saga. Or when not using Redux, at least think about using async functions.
In full general I want to keep async logic out of my components as much as possible. I also don't want the component rendering to drive the async logic.
have you lot had any success using the useReducer hook totally outside of redux? I feel like its bulky for certain operations but I all the same haven't found that "perfect" use-case for information technology nonetheless that makes it click for me
And then far non. Just I can imagine things. For example imagine a Game of life component with two actions, "evolve" and "set_cell". Basically any time when it is awkward to take exactly one mutation function (setter) for a slice of state. Other examples are a minesweeper game. Basically any time information technology is too awkward to etch unlike mutations on top of a single setter.
The other large benefit is that you can test the reducer without the component. And compared to redux, it withal has a smaller footprint. So information technology doesn't have the dependencies, you don't need to setup a store etc.
So, its React with the sharp edges smoothed away. Interesting. I am not a spider web developer, then forgive me if this is a stupid question, but can someone tell me, if you lot decided to use Solid.js as opposed to React, can you yet make use of all the 3rd political party React UI frameworks out there? Is it compatible with React in that sense?
Unfortunately, you cannot use React lawmaking within Solidjs[i] then you cannot make use of the huge ecosystem of react UI components/libraries. It isn't uniform in that sense. However, there is an "official" pick[2] for including Solidjs code inside React.
[1]: https://world wide web.solidjs.com/guides/faq#is-in that location-react-compat%2C-or-some-mode-to-use-my-react-libraries-in-solid%3F [2]: https://github.com/solidjs/react-solid-land
This commodity points out how ridiculous React is. This is just a simple timer, yet at that place are then many things you can go wrong. This article doesn't seem to even articulate the interval and so it runs forever. Solid solves some bug, only I don't know why everything has to be reactive. I accept never understood it, I just noticed that from knockoutjs onwards, every front end-end framework was based on automatically updating views based on state.
I create a library at github.com/thebinarysearchtree/artwork. To be honest, I don't know if information technology is going to work or non. It is simply javascript with no reactivity. When I rewrote a fairly typical large application that yous would find at almost corporations (not a giant tech visitor awarding), every component ended up being about 50% of the lawmaking of react, with splendid performance.
The problem I have with it that makes me uneasy is that ultimately yous are creating content in JavaScript, which I don't remember is platonic. The lack of HTML structure isn't a problem as devtools and then on show that. The problem is things like:
const label = label('Email:');
I want the HTMLLabelElement variable to exist called label... but that is the name of the function that creates it. Then there is the setText example on the github folio... I but didn't want to write label.innerText.. h3.innerText... etc etc .innerText. Variadic arguments are not ideal though, and when you have lots of elements with lots of attributes, eg:
it doesn't await like art, which is the point of the library. It is only hard to create content with JavaScript and not really the tool for the task. If I could solve that, I would be very happy with the library. It kind of needs JSX, but and so information technology is back to having the JSX variable auto-update the country and well.. I guess that is why knockout and so on do it. Maybe I could do just obviously HTML without state.
So yeah, I don't know. I mean, information technology does finish up being one-half the lawmaking. If you look at the todo example on my github folio, and compare it to the one on React's homepage or solid's homepage, it is literally half the amount of code with native paw-written performance. This continues on to real-world components, it is just that.. I am a perfectionist I judge, and I want it to exist elegant always.
anyway.. I haven't even finished writing the documentation.
I worked in React for a few years, although non enough to ever feel like I was an skilful. This article resonated with me considering I also got off the jitney considering of React hooks.
I've been using Lit.js for about a year now and something about information technology but clicks. I but wish it were more mainstream.
I prefer the very explicit first React case. While I'm non a web dev, on a larger project with a larger squad, implicit stuff generally makes things harder to empathise and more error-prone. I don't come across the boilerplate as a negative, I encounter information technology equally documentation.
I'm used to react and hooks,and right now I can't do whatsoever better. Doesn't hateful I similar information technology. The solid example here seems to accept a like complexity and implicit noesis as hooks just a slightly different syntax
Look what's the problem here? Considering yous didn't similar calculation [count] as a dependency to setEffect(()=>{},[...count goes here...]) yous wrote an entirely new framework?
It'due south not but that one example. Everything in react is similar this. I find react code hard to reason well-nigh because this type of friction exists almost everywhere. Solid is what I always wished react was, merely had a hard time articulating.
I don't know.
I used Vue.js for my last development, and I see no need to trade Vue.js for something that's both more circuitous and has less performance.
Every time I see stuff like this
componentDidMount() {
I go driven abroad from React. It looks haphazard. Seriously? What virtually
React's componentDidMount() is a lifecycle method that runs after a component mounts, once it's been inserted into the DOM. This is in contrast to componentWillMount() (now UNSAFE_componentWillMount(), considering information technology breaks when async rendering is enabled), which is chosen before the component mounts.
This naming scheme becomes even more important for the update lifecycle methods-- in addition to componentDidUpdate(), there's a shouldComponentUpdate() called earlier it (where yous can render true/imitation to tell React whether or non to proceed with the update) and UNSAFE_componentWillUpdate(), called between those 2.
Mayhap the proper name is trying to communicate it happens later on the component mounted instead of just before
Well, modernistic react is pushing folks to utilise the hooks model which jettisons the whole componentDidMount and other course functions. Now you utilize a side effect claw: https://reactjs.org/docs/hooks-outcome.html This is a little more clear that it's for side furnishings of the component being put in the DOM, but information technology does require a bit more than knowledge of react and hooks.
The reason behind this dissimilar naming convention comes from the variety in experiences of the original team. This will/did prefix instead of "on" comes from Mac OS X/iOS patterns and allows the name to convey the "when" of the listener. It is non "during component mounting" it is "after information technology did".
I guess this is just a limitation of JS the language showing itself. Other languages have actual attribute-oriented back up where before/afterward/around methods are very articulate name-wise and semantics-wise (if not e'er then clear without tooling support what happens if you lot come beyond a 'mount()' call). Maybe it'south time for a new JS framework! /due south
Fair point. I hinted with the thought of a new framework that you may be able to commodities something acceptable on peak of JS (I'm sure information technology's been done already in the past with some framework) peculiarly if y'all just want the before/afterward/around communication features of AOP without other stuff. Or possibly become into custom syntax transpiled to JS/TS-then-JS since no one seems to mind heavy build processes these days. For the nearly common industry use, I'd take to say information technology's notwithstanding Java's Jump AOP/AspectJ. Perchance it'due south not linguistic communication-integrated, only it'southward pretty close.
For an uncommon use example of what could exist possible:
(defmethod react.component:mount :after ((self counter)) ...) ; instead of componentDidMount (defmethod react.component:update :effectually ((self counter)) ...) ; instead of shouldComponentUpdate (defmethod react.component:unmount :before ((self counter)) ...) ; instead of componentWillUnmount ; (the react.component namespace qualifier could be whatsoever else and not necessarily typed out)
Nonetheless closely y'all integrate information technology with the language, having that mechanism generally bachelor seems better for naming and for providing new lifecycle functionality, without everyone having to reinvent the wheel and provide it in dissimilar incompatible ways. Just information technology's clearly not a big upshot.
I hate the whole javascript ecosystem to the core.
Hey I just finished my progressive web app with these 10 cool react components I found on NPM which fit surprisingly well into our startup's deject-native Vue interface.
I tried to put the code up on GitHub simply it wouldn't let me upload a 10gb repository (and that was without our proprietary fork of mysql :)
Too much snark.
We are running an enterprise-scale Angular xiii "SPA" that blows the prior platform out of the water.
Information technology simply depends on the team and the goal.
"That's a lot of code to write for an automobile-incrementing counter"
In reality, you will never need to write an auto-incrementing counter :) React gives yous a mental framework, you draw a page based on the state in a declarative way. The clever abstraction you make, the less you write the code, so information technology'south a little bit pointless to compare it with an auto-incrementing counter application, in reality has no use case at all.
For anyone who wants a thorough agreement of how to remember about React hooks in the context of things similar setInterval, Dan Abramov wrote a peachy piece breaking it down in particular several years ago: https://overreacted.io/making-setinterval-declarative-with-r...
This mail service helped hooks "click" for me, and once information technology did, I've absolutely loved them and now thoroughly savour writing custom hooks that greatly simplify my code.
Honestly my promise (and I admit as a total-stack but leaning dorsum-end developer to exist biased against JS) is that the futurity is in things similar turbo-stream, stimulus reflex, phoenix liveview etc - or in things like all_futures (essentially an ActiveRecord wrapper effectually kredis) - that we movement towards building reactive-apps by firing off events from the back-end and figuring out how to subscribe to them on the front-end
the amount of disruptive boilerplate I've seen to keep updated and maintained when a JS framework is loading front-finish country by making API requests against a backend and then trying to figure out how to continue those in sync when we could only be firing off SSR HTML over the wire and/or very sparse events that FE components can subscribe to or emit for literally no gain in functionality is beyond me
even better, simply add reactive sprinkles over what you need reactive and do the balance with standard MVC/Residue patterns, if most of what you are using react for is glorified forms, you don't need react for that! user your reactive sprinkles of notification toasts, and conversation channels...
I'm not saying there are no use cases for a JS framework, and I have a few I like, just that the switch to rails api only/separate react app has in nigh every example I've seen added tons of complication without a articulate win
Imagine you have a Rails controller with a form template and y'all want to have a section of the form show or hide based on the setting of other course elements, plain without reloading. Can you practise it? Yes. Does Hotwire/Stimulus make this possible? Yes. Can information technology exist done in a overnice like shooting fish in a barrel to use way? Yes. If you stretch beyond what Hotwire/Stimulus can allow yous practise, do you take to completely switch over to the "frontend applied science" path of single page applications (React/Athwart/Vue/Svelte/etc)? Also yes. Are the primitives you utilise in Hotwire/Stimulus in any fashion continued to the ones you'd use if the use case got even a trivial more than complex? Admittedly not. Why not just have one set of primitives that work for all applications?
It's not similar having some frontend templating logic or reactive forms or whatever is going to actually be harder than merely doing information technology in Rail if you are familiar and comfy with both. If you lot aren't comfortable with both, then that's fine.
Those are very unlike applications and the trade-offs involved are completely different.
In the -common- example OP seems to me to have a valid bespeak.
For forms-over-data business applications, sure it'southward fine. Information technology's tradeoffs effectually the organization use cases, potential/realized functionality, and team.
But I think that serving to public users with server-driven MVC for an application that goes beyond a pure content app has immediate and obvious limits in terms of what can practically washed, and the more than you lot attempt to overcome those limits the more you simply rebuild what is already available in the SPA side of things.
It'due south also inherently monolithic, significant that if y'all desire or need to support a mobile/native app for your public-facing app, you'll at present need to develop a new "interface" (an API), when you should accept already done that to enable the web app in the offset place. Is it really worth skipping API/UI separation on day 1 when you know it's going to be needed on calendar week 2?
You might say, information technology's fine, we're going to just make API calls for the Javascript, just so you've got an inconsistent availability of the functionality, and the second y'all hand that to some other team to consume you will have wished yous had simply built out all of the needed functionality directly in the API anyway.
Almost every criticism of React that I've read, goes away when you drive information technology from Clojurescript. If you haven't had the pleasance I suggest you accept it out for a spin.
Example of a full blown React component in Clojurescript:
Reminds me how vanilla hibernate is unusable simply Grails'/Peachy's GORM (congenital on Hide) is admittedly fantastic.
I've been using React since around 2016 and when Hooks were introduced I played around with it but didn't similar it at all exactly because of the reasons mentioned in this commodity. Certain it reduced quite a scrap of boilerplate code that came with class based components and enabled amend code re-usability outside of class inheritance or mixins but the disadvantages were too big for me personally to really consider using Hooks in a "greenfield" setting.
In my current project I'chiliad using Vue with Limerick API which gave me the exact aforementioned "aha" moment the author of this article had with SolidJS. Vue + Composition API is way more similar to SolidJS in principle than React + Hooks.
Pure function components in React with MobX for state management rather than the hooks organisation has worked out quite well for me.
I do, however, proceed finding myself wondering about jumping to Vue and VueX instead.
Ask me in five years, I judge.
We've used React with Mobx in commercial apps for 5+ years at present. React has been skilful for us BUT Solid is so much cleaner (and leaner).
Porting most React code to Solid is pretty like shooting fish in a barrel - mostly involves deleting things that are no longer required (useCallback, useRef, etc) and moving prop access into the JSX to enable just those specific attributes to be updated when state changes.
It has come up to the point where I really begrudge going back to working in our React code. Unfortunately those apps will still be around for a long time - but we won't be using React for green-fields projects.
Equally somebody who's quite enjoyed mobx I would encourage you to write upwardly your experiences.
I would promise that while -me- reading any such blog post is almost certainly going to exist irrelevant, it might pay off enough in recruiting/marketing/pure nerdery to exist worth the effort to write it upward.
Slightly OT: I'm ever amused coming to discussions like this 1, where people are (basically) complaining nigh the Virtual DOM and its implications. Information technology'due south bad for performance at scale, updates aren't minimal. And other stuff: SFC are hard to wrap your head effectually, I don't desire to write explicitly reactive code and so on. Some framework solves this by looking (somewhat) similar React but in the end doing something entirely different.
May I interest you lot in Athwart? It certainly isn't absurd and I actually practise hate it. But especially since the AoT compiler has been implemented, operation is quite good. In that location's templates, which some folks seem to love. Angular keeps in-memory references to all dynamic elements in a template and so they can be updated with high efficiency. It has class components. It has a lifecycle method that is called OnInit. So maybe requite it a whirl.
I've been using Angular in production for 5+ years. There was a yr where things were confusing, country updating all over the place, and general frustration. Simply once I grokked pure components, and embraced "data down, actions up", information technology all clicked and just made sense [0]. I find React obtuse in comparison.
Angular front-finish, Nestjs backend has fast go my stack of choice. It profoundly minimises context switching by having such similar paradigms across frontend and backend.
[0] - weblog series I wrote detailing Athwart best practices that I learnt along the way: https://link.medium.com/ncYgWgnK2nb
The whole "I hate angular" is a scrap sometime at this point. The latest versions are really quite elementary/powerful. We deed like it's nevertheless 2015 and we're jumping from angularjs 1.x to React. The bound was nice, yet turns out production-grade technology in React was non so nice.
I don't like the separation between template and code, I don't similar the programmer experience (slow and ofttimes malfunctioning VS Code extensions and slow builds, bad in-browser debug helpers), I don't similar how creating "ad-hoc" components is basically impossible.
I remember Zone.js is insane.
I know Angular very well. That'southward why I'm confident I can create high-performance applications using Angular. I firmly believe Angular has far too many pitfalls for inexperienced developers.
So yeah, I hate Angular.
If yous can't hate on your major dependencies confidently and at length, you probably haven't used them long plenty yet.
I generally spend much of my solar day writing perl. It absolutely works for me, but every time I encounter somebody who wants to -assail- perl I find myself disappointed by how short their list of reasons to hate it is compared to my own.
(ane of the most complicated JS codebases I work with on a regular footing is in angular, and the learning bend is a fucking cliff but yeah, in one case yous get to the top, I hold with everything y'all've said almost it)
`Athwart Language Service` is the only domain specific extension I've ever needed and its never been an issue. The template separation, as well as (s)css, I like organizationally compared to the chaos yous end upwardly in with big jsx-styled applications.
I find Solid.js a "ameliorate" React as well. In a new project that needs to be used past a lot of team-members, however, I still chose React.
Why? Because of the ecosystem! Exercise I demand accessible, headless components? Apply React-aria from Adobe! Do I demand state management? At that place are many established ones, I simply need to follow their best practices. Everything supports React, every hire speaks React, and it works, non like "just works", merely "... works" and, disappointing to the engineer inside me, this is non something I can trade in big projects.
Equally with any new JS framework technology, information technology will feel great until its flaws, warts, deficiencies and limitations are inevitably discovered equally complexity rises, and which are and so addressed in the adjacent JS framework.
Great bulk of my projects are data dashboards and I struggled with React for some time because of its top-down model - information technology can hinder functioning really badly. If one of your points on scatterplot should be marked, you need to carefully laissez passer this prop through few memoization layers, so whatsoever other points won't try to re-return.
I've been on this quest for a long time, considering I similar React model. So I had fun with putting observables in my app (kefir and karet from calm-js and my ain thing with xstream), I tried custom selectors with redux and all 'like-redux-but-simpler' libraries, I besides tried recoil. These solutions tin piece of work and worked for my apps, just it felt like I was fighting against React.
Solid was squeamish. Information technology provided necessary tools to write interactive information visualisations with ease and in performant mode. It has quirks but they are manageable - my team besides learned and contributed to projects in Solid.
First, the concept of "component functions" that are more like factories. It is non groundbreaking (reagent had this idea long ago) but is quirky. Thankfully, half hour with Solid playground and everybody can encounter what code is generated and how it works nether the hood. It is really predictable but also tangible - you can play with just part of your app in playground if something is unclear.
Second quirk is props object. I empathise the trade-off but it trips users (me included) that you tin't but care for it every bit regular object. Sadly, only solution for this is lint rule - yuck. Just information technology is much simpler dominion than hook rules - but don't destructure props.
In the stop, Solid is dandy tool for "web apps". Retrieve virtually dashboards or diagram editors. Cheap components, fine grained reactivity, focused updates yield great performance results without jumping through hoops.
Tin anyone explain the point of the virtual DOM and why it's not a source of huge performance issues? What I mean as soon as you retain a reference to a DOM chemical element, it'southward lifetime becomes managed past the JavaScript gc - let'due south say you build a paginated gallery app in pure HTML and an spa - in the kickoff case, the browser knows that as soon as y'all navigate away from the page, all those prototype thumbnails are gratuitous existent manor, at the latter instance it first needs to look for the spa to release references to the underlying html objects, then the gc needs to run, at which point information technology tin become rid of it.
The reason for the virtual DOM: in react, the unabridged world is a function that gets rerun on every render. The whole point is to exist able to define some state and and then render the whole earth in accordance with that new state. When react was conceived, Dom updates were very slow and could bottleneck the application.
Knowing that your entire UI is running within a role that gets re-executed with every render, gives a tremendous amount of safety and predictability to your awarding and makes testing a breeze. But you tin can't actually rerender the whole world every time because functioning, so instead React relies on a JavaScript object to concur a representation of the UI, then surgically updates only the pieces that need updating. This was React'south big matter.
The reason people want to move away from virtual dom is because browsers have gotten faster and now the Dom updates aren't the biggest source of overhead.
https://svelte.dev/web log/virtual-dom-is-pure-overhead
It is a huge performance result.
I tried to do a pokedex in react, you have to use a virtual list, considering react/virtual dom is too deadening, doing any operation on a plain list with 1k element, similar filtering lead to multiples seconds freeze.
This as well pb to a lot of issues, similar non being able to ctrl+f text being out of screen in a virtual list.
I don't understand your issues hither. I built a customs app for a hockey league that manages around 120,000 players in the DB. I practise tons of loading, sorting and various algorithms on the data. I've never in one case had React exist my bottleneck.
Rendering a page server-side and delivering it to users is about as inefficient a process as y'all tin can get unless you accept massive resource dedicated to an optimization almost no ane needs anymore. The virtual DOM is extremely efficient, it just needs more memory and CPU cycles on the customer which are resources readily bachelor. Browsers are very good at managing this in 2022.
Btw, your code in that article is completely irrelevant... I would not be showing people that article in 2022.
I bet you lot don't brandish the 120k players at one time on the forepart, you lot use some sort of virtualised component (like ag-filigree) thats put in the DOM only what is displayed on screen, and keep the whole set in memory.
Information technology crusade an issue: now the search in document browser characteristic will not work properly.
This is acceptable the usecase you are describing(due to the huge dataset), merely a lot of interfaces use such virtual list, and it's an PITA for the user.
Take Azure DevOps for example: In a lot of place, y'all can't ctrl+f a projection outside the screen, even if it exist, you take to scroll to it.
> Rendering a folio server-side [...]
Nobody talked about server side rendering there.
> The virtual DOM is extremely efficient
Did you lot read the article I linked ?
The virtual DOM is non "extremely efficient" information technology's only skillful at removing uneeded DOM modifications. Not doing these uneeded modifications in the start identify is faster.
I have hit a betoken where I've moved my browser from running locally on my laptop to running on a hetzner dedicated server over VNC because it performs ridiculously better so "readily available" is obviously an unfortunately variable claim.
I would note nevertheless that my laptop is not entirely recent and I'thousand using firefox and my big pain point has been React Native Spider web apps like web twitter. So yous're probable still by and large correct, and the question inevitably becomes "how much more often than not is plenty for whatsoever given application".
https://tigervnc.org
Does some impressive compression tricks that results in it being remarkably snappy.
You may prefer to run Xvnc directly rather than apply the wrapper script, depends how you want to set everything up.
I will exist honest here that my setup is non properly automated yet considering it'southward inside a jail on a FreeBSD install and the underlying box gets good plenty uptime that my current half-assed approach hasn't withal annoyed me into finishing it.
There weren't any interesting gotchas though.
Great article. The fact that Athwart, the framework built by the visitor who too builds the earth's well-nigh popular browser, does not have a virtual DOM, is very telling.
I wouldn't acclaim angular for the functioning either.
Building apps on it show consistent subpar functioning.
generally speaking, Angular handles dom manipulation amend than React and Vue. Angular has managed to simplify its enterprise/product applicability and performance is a offset-order characteristic that's hard to f up. React -- you can f performance upward before you're washed writing your outset component.
Information technology'south really a terrible commodity that has no relevance in 2022, and it is even misleading for 2018 standards.
I ran a profiling tool. I searched "zz" then deleted these.
Deleting information technology caused a 120ms UI freeze (and I notice it :p):
Profiling report: https://share.firefox.dev/3C3OhIq
Given I had slightly more entries (a hundred more than) and that I had manner more node per entry, information technology led me with way worse performance.
Instead of a evidently list I take a little summary card per pokemon (which is why I have more than node per entry).
The naive implementation in Vue run flawlessly(sadly no preview):
https://github.com/Kuinox/kuinox_pokedex/
Note that the react implementation exercise weird affair considering I tried to get effectually the outcome without success.
Regarding the example under "Reactivity, not lifecycle hooks":
Does the <Counter /> component reference the same outer "count"? So is "count" hither global or local to the component? In other words, what is the scope of "count"? Does it change based on where information technology is placed? If I create multiple <Counter /> components, do they all reference the same "count" or is information technology different for each component?
Sorry this question might seem naive if you are experienced in SolidJS. I haven't given SolidJS a shot yet (though it is on my list of things to check out).
I call up the count variable is quasi an Rx subject, information technology has identity and whatsoever code using information technology is keeping a hard reference on information technology. It would probably be GC'd if nobody referenced it. In my understanding, yes, multiple components would use the same case of count.
Yeah this is correct. The trick to this is that the subscriptions happen in our JSX and hooks. And really is just a nested tree of `createEffects` if one ever re-evaluates or is disposed it releases its kid computations. So while the lifecycle isn't tied to components it is still hierarchically structured. Ie.. places where logic tin can co-operative becomes the owning telescopic, like conditionals or loops. Then Signals like count don't really matter where they alive and will alive equally long as in scope or referenced, the rendering still largely defines how long things are around.
I've spent the past month kind of rewriting parts of Solid in an attempt to better understand information technology, and coming from React the way Solid works is just then much more beautiful, it feels liberating.
There'due south no rules of hooks, no dependencies arrays, no stale closures, no wildly unlike resulting performance depending on where exactly yous put your components boundaries, no VDOM at all, no props diffing, when I change the country respective to an aspect or property that only gets updated immediately, the way deep DOM nodes structures are created is sooo much more efficient... it's amazing!
Equally part of my annual routine, I'm exploring the "latest and greatest" JavaScript UI library. Solid.js'due south performance seemed compelling. xv minutes into documentation and this is what I encountered. Can y'all gauge which one of the ChildComponent* updates when the text input on the parent component is updated, and the props passed to the child? The answer is three, 4, 5, six. My takeaway is this: in that location are multiple ways of doing information technology right, but likewise a handful of gotchas. The but way to be safe is to go along the mental model of these partitions while you develop, test, debug, and code review. Equally a code reviewer, yous can easily have the wrong code. For now, I remain skeptical of Solid.js as solving the complexity woes of Reactive programming. I'm not sure React.js is amend.
Or Vue either to be off-white. Similar rules in the Vue'due south setup function. It's how reactivity works in JavaScript. Basically don't destructure or access values out of of primitives or JSX. That'south basically the gotcha.
Unfortunately it'southward the cost y'all pay for portability thus far. You can build your own language effectually this like Graceful but then composability is limited (need to rely on other mechanisms). You can brand the updates coarser grained like React only then you demand a dissimilar mechanism(like VDOM diffing) to apply updates granularly. I imagine this situation improves in the futurity but we haven't gotten there yet.
Out of involvement, what language features exercise you see JavaScript needing to support these kinds of fine-grained reactive updates, and to let destructuring?
I'd assume something like es6 proxies for archaic values would be needed, merely that, nor congenital-in reactive primitives, are being discussed currently every bit far as I know.
Personally, I'd love to see reactive `[].map` equivalents (no need to employ <For> components), only that's possible today with a reactive wrapper or (god forestall) patching the prototype.
Grade components are fine for the simplest examples, but the moment they offset increasing in complexity, they get a bit of a mess. Sharing functionality across multiple components becomes tricky with course components (with the only real choice being HoCs / return props). You necessarily have to spread logic across different lifecycle methods.
Hooks allow you to package code together by functionality, and consequently permit you to easily excerpt and share said functionality in a very composable style.
This is my go to for visualizing the difference: https://i.imgur.com/e9K8vfz.gif
> Hooks permit yous to bundle code together by functionality, and consequently let you to easily extract and share said functionality in a very composable way.
You're using React. The mechanism that enables code reusability is through composing components.
There'south nothing wrong with class components even for the most complex logic. The simply downside is the customs has moved on and by and large adopted hooks and functional components.
> The mechanism that enables code reusability is through composing components
If yous think that this:
is more desirable than this: Then go for information technology I approximate.Although you'd accept to somehow ignore the fact that yous'd end up with an even bigger mess if you desire these intermediate functionality steps to collaborate with the parent component in a non-little fashion, ..
Needless to say, I have written such return-prop and "renderless" components in the past, and I come across very picayune upside compared to hooks.
Thats interesting. Then in your 2nd instance, am I right in proverb the variables 'apple' and 'slicedApple' are react JSX that you lot are ultimatly passing through to <DinnerPlate/> to return on the screen? If so, yes, that is fairly intuitive.
'apple tree' and 'slicedApple' would more likely be strings / objects / arrays in the real globe. Maybe this still woefully contrived version is clearer? I don't retrieve deal with more braces right at present to bring the culling into existence unfortunately
Thanks for the viz, haven't done React in a while and so it's interesting to see how things have improved. The new image seems alot meliorate modularized and the logical structure seems easier to follow, combined with it taking advantage of newer JS features.
I think in the class globe this is ordinarily washed past writing a service and injecting it on the constructor of the parent class. Since, React doesn't have DI built-in, it becomes problematic with the injection. hooks are essentially classes imo.
How does it become problematic? Yous merely pass in dependencies every bit arguments to functions or components.
It's certainly a leak. That setInterval is going to be holding the closure context alive which volition reference the component in many frameworks.
The setInterval will too continue firing causing, wasting CPU and battery.
It's difficult to accept whatsoever examples hither seriously without showing proper cleanup that would pass lawmaking review.
Skilful to see other people spotted that, I noticed it immediately and had a "in that location's a bug! a bug!" alarm bell ringing in my head throughout the rest of the article. I may accept some sort of setInterval related PTSD.
The upshot is more about non understanding how React works and how to employ hooks. The setInterval example is hands solved. No, you can't only half-assedly guess your way to a right solution.
Also, composing asynchronous behavior with useEffect is also non a good idea. Don't abuse useEffect as an Event Handler (also much). Remember nearly using Redux (+ thunks/saga) or something similar.
This looks a lot like my current favorite state framework (which yes is done by Facebook people), Recoil - https://recoiljs.org/
Your naming still reminds me of the RxJS and full general reactive programming prototype I've ever pined after... some combination of the two would exist my UI state management holy grail.
Many devs take succumbed to the siren song of event sourcing. And many code bases have sank on those rocky shores.
I'g surprised to encounter so many negative opinions nigh React. Surely, I can't exist the only 1 that truly likes React and finds myself beingness extremely productive and making impressive apps with it.
You're definitely not the but i. Just I find it refreshing to hear some people voicing many of the complaints I've had about React for years. Up until very recently, criticizing react seemed to be almost unheard of.
Accept you tried solid/vue? If so, consider adding your perspective of what react does better.
I haven't used Vue in a really long time. Last fourth dimension I used information technology, Evan You had just shipped Vue 2.0. Using Vue was honestly a fantastic experience, and a great stepping stone to get off of Angular 1.x. I actually enjoyed its arroyo to data binding and unmarried file components where the styling, functional logic and templating was all contained in a single file.
At the time the promise of React was very far-fetched: using JavaScript generate your HTML markup. I actually was really adamant to use React and held off on it for a long time. However, once I gave it a fair shot, I was blown away by how intuitive it felt to use. I think the mental models it champions really helped bulldoze its adoption.
While information technology was a pleasure to apply, I was always wondering about other frameworks. Just where React really locked me in was in its support. `create-react-app` was an incredible achievement, tbh. It made information technology so easy to first using React and have all of the bells and whistles out of the box without ejecting. Then, once y'all exercise squirt, all you have to practise is alter your Webpack configuration and you can get all of the additional stuff you want. The community as well made incredible packages, similar Downshift and Emotion, which farther fabricated React an attractive tool.
Over the years the React team has kept innovating it. Hooks fabricated it so much easier to just write functional components, which has always been a core tenet of React (admittedly, Solid.js was using hooks before React). More recently, React added the concept of SSR/hydration to its framework. Initially a lot of people made fun of it considering it was like we went back to HTML generation on the server, simply and then developers realized that you become the all-time of both worlds: immediate markup from the server with the reactivity and snappiness of a single-page application.
Because of SSR we now have innovative frameworks similar Adjacent.js and Remix. I know Vue iii/Nuxt.js exist at present, and I know Solid.js exists at present, simply at present that I've started using Remix I'm trapped in React land again (and honestly, couldn't care less). Remix is so freaking good and information technology'south such a freaking improvement from when I did SSR in 2019 that it's hard to come across myself using another framework.
This is kind of a bad reply, only at least I can show you why I'm locked into React I haven't tried whatever other framework (I too genuinely enjoy using React).
There are some things I don't enjoy about React. I don't enjoy how prevalent Redux is when developers remember well-nigh global land. I too don't retrieve contexts are a expert enough solution (having a adept reactive model would have definitely helped here). At that place are other things I don't like about React: I don't similar how often it calls functions; it's extremely wasteful in big applications if you lot're non conscientious. And the semantics of `useEffect` are really murky for newcomers (and fifty-fifty sometimes for experienced developers).
If there is something similar a Remix equivalent for Solid.js I'll requite Solid.js a shot. But right now I'm in dear with Remix. Maybe I tin can use Remix with Solid.js? I'll take a look.
I dearest solidjs, but the similarities to React are the hardest part for me. The semantics are so similar, just the mechanics are the polar opposite.
In react, everything is a role and all your code runs on every render unless you specifically tell it not to. This actually encourages a certain manner of writing lawmaking and provides a lot of guarantees almost prophylactic and telescopic.
Solid is literally the polar reverse, your lawmaking runs once, and only the parts that you lot specifically make reactive are reactive. This allows for much finer-grained updates and performance.
The mental models are so different because they are optimized for different things. React allows for developer sanity (cue all the people who worked on i lousy react app telling me that information technology doesn't) and Solid optimizes for speed and simplicity.
Solid is very well designed though. Ane of the features I loved is that Ryan specifically congenital it to work equally possible to vanilla html/js so you can re-create old stack overflow answers.
I had the same problem: spending time trying to figure out why something didn't paint. You also can't use restructuring the way yous might expect. Information technology'southward a absurd library, though. I remember yous just need to go on a different fix of nuances in mind when using information technology.
Agreed, and typescript is essential. I'm withal new enough to the patterns used in solid that I tin't always tell whether a prop is a value or a signal, just with TS it's footling.
and Solid JS runs very shut native JS speed! Whatsoever i making a Reactive Native Connector for solidjs? Vue Native was already using that connector. with that, Solid JS volition exist ultimate isomorphic lib to utilise.
I wonder if there's an immediate mode framework for Js, in the vein of IMGUI for C. If people are wondering what that is, information technology'south basically this:
This seems like a huge step back from declarative UIs, any reason why yous would say it'southward preferable?
Performance, for one. This method can easily avoid allocating an object for every div (since it turns into a method call, non something that needs to return an object), compared to React's render() method.
Another scenario outlined in the article of rendering a row of buttons, each with it's ain click handler, that needs to allocate a lambda for each push every render. Alternatively, using map() and filter() also allocates lambdas and temporary arrays.
All this can be replaced with a simple for loop similar:
Compare this to the React-ish pseudocode: Readibility-wise, it'south sort of an acquired taste, I'g not saying information technology looks better than JSX (merely it'southward a hell of a lot readable than React.createElement, so some syntactic sugar might exist put on top of it).I suspect that the nature of the DOM ways that existence able to practise that in the get-go place would really require a virtual DOM w/diffing assuming y'all're targeting browsers.
However that'due south probably obvious, so: Assuming you're considering greenfield / blueish sky thinking hither, it's worth noting that v8 has had so much money and engineering hours sunk into information technology that the react-ish pseudocode probably doesn't brand near every bit many allocations as a naive reading of the code might expect.
(a good friend of mine was very surprised to discover that v8's JIT is expert plenty that naive javascript code was basically competitive with FFI-ing out to C++ just because the node FFI layer introduced sufficient overhead that the JIT managed to catch up ... I am not a compiler wonk so delight don't accept this equally a remotely skillful pronouncement but "it is, in fact, quite hard to overestimate v8 these days" seems to be a solid heuristic)
>the react-ish pseudocode probably doesn't make nearly every bit many allocations as a naive reading of the code might await.
Who knows, if V8 manages information technology to turn it into a for-loop? I don't, only afterwards a quick googling, as of 2018, it certainly didn't: https://github.com/dg92/Functioning-Analysis-JS
The trouble with JS is that the execution model is so nebulous, that functioning communication basically boils downward to - trust in Google.
Everyone goes on about operation but unless you are doing something extremely complicated or you have fucked stuff up in an extremely bad way, the actual part of React apps which is rendering to vdom and diffing to dom, in my quite long experience with it, is very rarely a trouble, and not enough to warrant a stateful imperative approach.
i think an immediate mode UI library would make sense if y'all desire to render to a canvass or a similar "backend". mayhap for things like games, or some interactive graphic things
but if yous desire to render to the DOM —and you lot want to use the DOM if you want to accept decent accessibility, or not accept to reimplement all the complex user interactions that the browsers take care of— then i call up an immediate mode framework might have a bang-up impedance mismatch with the DOM, every bit the latter is a retained fashion GUI model
Ane of the most compelling things about Solid.js is that it integrates some of React'south almost important (IMO, probably aside from the central idea of UI every bit a part of state) ideas for writing applications, Suspense, ErrorBoundary, useTransition.
Vue hooks avert the closure/scoping issue mentioned in the physician. Very similar conceptually, only I notice Vue's implementation a fleck nicer to employ
Took me 30 minutes to get up and running in Vue. Week 4 of this chore and I still can't unfuck myself with React.
I'm missing some toes from the quondam react lifecycle methods. The vanilla hooks were easy to utilise, reason about, and robust against misuse in a mode the lifecycle methods weren't.
I could run into custom hooks existence more than unsafe and difficult, only Higher-Social club Components are besides.
I always wonder why all JavaScript customer-side frameworks have such singled-out design.
No other dev surroundings for building GUIs has react-like components.
What'due south so special most the web that nosotros go along creating frustrating frontend frameworks for?
I personally love the front finish frameworks, and I don't find them frustrating at all. Knockout was a workhorse until angular came along. And so vuejs. And at present I use sveltekit for pretty much any web app.
The frameworks are popular because y'all can build things incredibly chop-chop one time y'all know the ins and outs of your framework of choice. The component-style pattern, the endpoint design, so much is just driven by the needs of spider web-based development and the framework creator'southward preferred way of abstracting abroad some of the challenges.
The browser was intended to render documents, not applications.
In particular, HTML has a tree construction, which means that things that are semantically related on the page and update together are frequently miles away from each other in the tree.
And the page in the browser is part HTML, function CSS, function Javascript. Frameworks try to let the programmer work in JS only and generate the rest.
And finally, much of the awarding'southward state is often kept in a backend, and access to it a asynchronous.
I think that's why Web evolution is and so distinct from other UIs.
One reason is probably that creating UIs programmatically was historically very cumbersome in JavaScript due to various issues that are no longer relevant. That means everything had to be HTML-based hybrids of some sort.
Considering at that place are a lot many js devs than others. Hence js ecosystem is significantly larger.
Later years of using Knockout and Athwart/RxJS, I'm not at all convinced that adding Observables to React is going to lead anywhere interesting.
This is the same code in Graceful.js
# Counter.graceful
<script> permit count= 0
</script><div>The count is: {count}</div>
Probably the equivalent would exist a custom store, something like this:
Yep. Looks sort of like the Solid case in the article. It's basically my auto-response to Graceful syntax. Once y'all practice annihilation in Svelte information technology is more than or less the same thing.
But dissimilar priorities. In Solid yous tin take that code as is in the component and hoist it out to a function above and presto.. store. It's still thing everywhere. Same patterns, same usage, same building blocks. No new APIs, no new syntax.
It is nice when first learning not to worry about Svelte Stores and apply the convenient syntax. It is also nice to acquire something once and use information technology everywhere.
Knockout.js was/is wonderful, I'm not sure why information technology never took off the way angular or react did. I practise appreciate jsx though and so I'll be looking into Solid.
As far every bit I could tell, around that time (and fifty-fifty now to some extent) the amount of activity on StackOverflow is used to measure out the popularity of a project.
Angular had a "made by google" kind of logo on its website, indicating to many people that it's of high quality and worth adopting.
Just Angular was also so convoluted and had so many bug that so many people kept running into random problems all the time and had to enquire questions about them on SO. This signals (incorrectly) that Athwart is popular, driving more than people to believe information technology's worthwhile to adopt it.
Knockout had neither. Information technology was not sponsored by a corporation. And information technology was so adept that you hardly ever meet random bug.
Ultimately it was eclipsed by React and Typescript because lack of type checking for the html templates means it'due south hard to scale it volition to large projects.
The bug with knockout were:
very hacky syntax embedded into html. Sometimes you lot had to fifty-fifty employ some kind of comment notation considering there was no entry point into the html to add data properties or any it had.
it was slow.
the observables weren't variables y'all could utilise similar plain JavaScript variables
it has the same problem as React - state-based algorithms are non very good ways to solve problems (if (showDialog && !open && ranOnce). You have to keep creating more variables to stand for more states instead of using normal programming language concepts, and then all of the observables ping around and become complicated.
It kinda is, but it'due south more than than just JSX. Solid was basically born out of Knockout and is in many ways a continuation of Knockout, but it has some relatively significant changes and additions to brand this approach more than viable, specially for large long standing projects. JSX is more of a quality of life thing, you lot don't even accept to use it, Solid'southward runtime exists completely separately of JSX and tin can piece of work bang-up without it or fifty-fifty potentially be integrated with other templating languages.
This is really interesting. I'chiliad happy the author covered the effects side of things considering this is where I've had some challenges with non-footling React apps. Sometimes effects can exist very complicated and result in React getting stuck in an infinite loop.
Before you say information technology'southward because I'chiliad "doing it incorrect", Material UI's website had this problem for quite a long time. That issue required doing manual refreshes to not trigger the infinite loops (something you would but see in the debugger). This problem in reactivity is a event in React that even the best devs can struggle with. My solution was simple... employ useEffect less. Depend less on reactivity.
The bottom line for me is that I experience like I can achieve annihilation in React, just the devil is in the details. There are and then many scenarios that I would need to vet with Solid.js, simply if it works better at managing a complex app's reactivity, it could be very compelling.
I am fundamentally skeptical of anything that needs a runtime for anything other than security and profiling.
I am extra skeptical of whatever framework that needs 50mb memory baseline.
I am triple skeptical of anything that uses brand-new packages and components like legos.
*Iterations on React are welcome.*
Well, you lot can be skeptical, and the enterprise front-end engineers are going to go right on using that stuff because it scales to large codebase.
Yes, right up until said startups and enterprises ane. cannot afford the outrageous deject expense or 2. Need to scale to low-power devices (such as wearables) and to customers who are security conscious
Don't worry, they're doing fine. Anyway, we were talking nearly React, to which none of those objections apply.
What feels like complete insanity when it comes to React is that it needs compilation to piece of work: This is not Javascript and it volition need to exist compiled into Javascript before it gets executed.
Only you lot can do the same in Javascript:
Using regular Javascript makes my life a 1000 times easier than having to go through a compiler to make things work in the browser.This is another area where Solid has an advantage over React. With React yous could utilise Hyperscript functions so the above JSX would be
React.createElement('div', zilch, `The count is: {this.land.count}`).
With Solid yous get the pick, you could use JSX, Hyperscript functions or template literals like in your case. Solid does recommend using JSX because there are some tradeoffs to using template literals without compilation, but it nonetheless maintains most all of its qualities AFAIK and in the big framework benchmark Solid with template literals is the fastest template literals implementation.
With Solid you don't even accept to utilise any templating languages, you can have care of rendering yourself using the tools that the framework gives you. Solid at its core is more of a capable land management library similar to MobX just designed to be used as the just reactivity engine different MobX which is ordinarily used on top of React.
Using template literals to represent html is a security effect. If the state comes from the user, they tin can add script tags into the html. People effort to solve this with tagged templates, but so if you lot forget the tag, you have a security issue again. Lit checks for this, simply the fact that it has to check means it is less secure than not using tagged templates. There are libraries on github for creating sql using tagged templates which have the same security issue. The problem is that if your part works with both tagged templates and plain strings, when you forget to add together the tag, you will never know.
How is that unlike with React?
And how is information technology a problem? A rendering engine would set the html of some element to the html I call back?
This ...
...does not execute the script.Doesn't that brand an hard life for the linter that now has to decide which template string represents a (complete) chemical element and which is just text/whatever? I prefer the outset solution because it's much simpler to parse
Did anybody use Observable Hooks however? https://observable-hooks.js.org/
This seems to exist quite a expert way to compute and use complex country to a component. In my opinion better than useReducer().
Merely to be honest, for about components useState() and useEffect() are totally plenty. And if you practise something wrong like in the counter example, you see it right away.
Isn't this only the Vue composition API dressed upwardly to look like React? I haven't done frontend in a minute, then apologies if this is ignorant.
Mostly except in that location is no VDOM, the reactivity applies right downward to the DOM binding. And it predates Hooks and Vue's Composition API.
> That's a lot of code to write for an auto-incrementing counter.
Is information technology though?
I hateful I happily write more than code for a single-folio Vue component for something like this.
Terseness is non ever a virtue.
> Terseness is not always a virtue.
This is a subjective thing, right? Personally, I detest boilerplate: either it'southward a lark considering it'southward boring and superfluous, or worse it's long and it's wrong. Regardless, it adds to the cognitive load when maintaining code.
Yeah, definitely, hence the "not always" in this instance.
There are several terse syntaxes I actually similar. I'm but non convinced it'south a virtue in this context.
The vue lawmaking for this is pretty terse anyhow to exist honest. A single variable in data, a call to setInterval in the created hook and a few lines of html with template formatting. It's extremely clear what'south going on besides.
I tried several React alternatives.
At this phase, size of community is a really important factor, overriding many other factors.
It's just incredibly important for there to be tools back up, questions answered on stack overflow and a customs of people developing related software.
At this stage there's but actually VueJS, Angular and maybe one or 2 others with community big enough to justify irresolute.
Instead of vDOM, solid.js uses <template> - existent DOM elements + cloneNode().
And that'south doubtful decision. Each alive DOM element is about 100-200 bytes in memory.
While in React (PReact, Mithril) this JSX expression:
is this: 5 or so times less.In other words: needs to be tested on large DOM structures.
That's only a component template though. When yous produce big DOM copse, y'all unremarkably do so by rendering your components a lot of times, not by having a lot of different components
I merely dove back into react after a while in vue and deep in some backend systems.
I dear the new ergonomics (hooks, useEffect, redux tools) but I definitely hitting the verbal issue OP mentions about immediately.
I don't feel that the solution react provides is too out there, just agree information technology could be amend. The react ecosystem still makes it worth the i or two "could be betters" for me.
Y'all may need to remember about how you lot implement asynchronous side effects. Declaring them with useEffect quickly gets annoying. Look for things like thunks or saga. Or when not using Redux, at least think about using async functions.
In full general I want to keep async logic out of my components as much as possible. I also don't want the component rendering to drive the async logic.
have you lot had any success using the useReducer hook totally outside of redux? I feel like its bulky for certain operations but I all the same haven't found that "perfect" use-case for information technology nonetheless that makes it click for me
And then far non. Just I can imagine things. For example imagine a Game of life component with two actions, "evolve" and "set_cell". Basically any time when it is awkward to take exactly one mutation function (setter) for a slice of state. Other examples are a minesweeper game. Basically any time information technology is too awkward to etch unlike mutations on top of a single setter.
The other large benefit is that you can test the reducer without the component. And compared to redux, it withal has a smaller footprint. So information technology doesn't have the dependencies, you don't need to setup a store etc.
So, its React with the sharp edges smoothed away. Interesting. I am not a spider web developer, then forgive me if this is a stupid question, but can someone tell me, if you lot decided to use Solid.js as opposed to React, can you yet make use of all the 3rd political party React UI frameworks out there? Is it compatible with React in that sense?
Unfortunately, you cannot use React lawmaking within Solidjs[i] then you cannot make use of the huge ecosystem of react UI components/libraries. It isn't uniform in that sense. However, there is an "official" pick[2] for including Solidjs code inside React.
This commodity points out how ridiculous React is. This is just a simple timer, yet at that place are then many things you can go wrong. This article doesn't seem to even articulate the interval and so it runs forever. Solid solves some bug, only I don't know why everything has to be reactive. I accept never understood it, I just noticed that from knockoutjs onwards, every front end-end framework was based on automatically updating views based on state.
I create a library at github.com/thebinarysearchtree/artwork. To be honest, I don't know if information technology is going to work or non. It is simply javascript with no reactivity. When I rewrote a fairly typical large application that yous would find at almost corporations (not a giant tech visitor awarding), every component ended up being about 50% of the lawmaking of react, with splendid performance.
The problem I have with it that makes me uneasy is that ultimately yous are creating content in JavaScript, which I don't remember is platonic. The lack of HTML structure isn't a problem as devtools and then on show that. The problem is things like:
I want the HTMLLabelElement variable to exist called label... but that is the name of the function that creates it. Then there is the setText example on the github folio... I but didn't want to write label.innerText.. h3.innerText... etc etc .innerText. Variadic arguments are not ideal though, and when you have lots of elements with lots of attributes, eg: it doesn't await like art, which is the point of the library. It is only hard to create content with JavaScript and not really the tool for the task. If I could solve that, I would be very happy with the library. It kind of needs JSX, but and so information technology is back to having the JSX variable auto-update the country and well.. I guess that is why knockout and so on do it. Maybe I could do just obviously HTML without state.So yeah, I don't know. I mean, information technology does finish up being one-half the lawmaking. If you look at the todo example on my github folio, and compare it to the one on React's homepage or solid's homepage, it is literally half the amount of code with native paw-written performance. This continues on to real-world components, it is just that.. I am a perfectionist I judge, and I want it to exist elegant always.
anyway.. I haven't even finished writing the documentation.
I worked in React for a few years, although non enough to ever feel like I was an skilful. This article resonated with me considering I also got off the jitney considering of React hooks.
I've been using Lit.js for about a year now and something about information technology but clicks. I but wish it were more mainstream.
I prefer the very explicit first React case. While I'm non a web dev, on a larger project with a larger squad, implicit stuff generally makes things harder to empathise and more error-prone. I don't come across the boilerplate as a negative, I encounter information technology equally documentation.
I'm used to react and hooks,and right now I can't do whatsoever better. Doesn't hateful I similar information technology. The solid example here seems to accept a like complexity and implicit noesis as hooks just a slightly different syntax
Look what's the problem here? Considering yous didn't similar calculation [count] as a dependency to setEffect(()=>{},[...count goes here...]) yous wrote an entirely new framework?
It'due south not but that one example. Everything in react is similar this. I find react code hard to reason well-nigh because this type of friction exists almost everywhere. Solid is what I always wished react was, merely had a hard time articulating.
I don't know.
I used Vue.js for my last development, and I see no need to trade Vue.js for something that's both more circuitous and has less performance.
Every time I see stuff like this I go driven abroad from React. It looks haphazard. Seriously? What virtually ...
I'k used to clean naming conventions similar
When does on_mount run?
React's componentDidMount() is a lifecycle method that runs after a component mounts, once it's been inserted into the DOM. This is in contrast to componentWillMount() (now UNSAFE_componentWillMount(), considering information technology breaks when async rendering is enabled), which is chosen before the component mounts.
This naming scheme becomes even more important for the update lifecycle methods-- in addition to componentDidUpdate(), there's a shouldComponentUpdate() called earlier it (where yous can render true/imitation to tell React whether or non to proceed with the update) and UNSAFE_componentWillUpdate(), called between those 2.
Mayhap the proper name is trying to communicate it happens later on the component mounted instead of just before
Well, modernistic react is pushing folks to utilise the hooks model which jettisons the whole componentDidMount and other course functions. Now you utilize a side effect claw: https://reactjs.org/docs/hooks-outcome.html This is a little more clear that it's for side furnishings of the component being put in the DOM, but information technology does require a bit more than knowledge of react and hooks.
The reason behind this dissimilar naming convention comes from the variety in experiences of the original team. This will/did prefix instead of "on" comes from Mac OS X/iOS patterns and allows the name to convey the "when" of the listener. It is non "during component mounting" it is "after information technology did".
I guess this is just a limitation of JS the language showing itself. Other languages have actual attribute-oriented back up where before/afterward/around methods are very articulate name-wise and semantics-wise (if not e'er then clear without tooling support what happens if you lot come beyond a 'mount()' call). Maybe it'south time for a new JS framework! /due south
Fair point. I hinted with the thought of a new framework that you may be able to commodities something acceptable on peak of JS (I'm sure information technology's been done already in the past with some framework) peculiarly if y'all just want the before/afterward/around communication features of AOP without other stuff. Or possibly become into custom syntax transpiled to JS/TS-then-JS since no one seems to mind heavy build processes these days. For the nearly common industry use, I'd take to say information technology's notwithstanding Java's Jump AOP/AspectJ. Perchance it'due south not linguistic communication-integrated, only it'southward pretty close.
For an uncommon use example of what could exist possible:
Nonetheless closely y'all integrate information technology with the language, having that mechanism generally bachelor seems better for naming and for providing new lifecycle functionality, without everyone having to reinvent the wheel and provide it in dissimilar incompatible ways. Just information technology's clearly not a big upshot.I hate the whole javascript ecosystem to the core.
Hey I just finished my progressive web app with these 10 cool react components I found on NPM which fit surprisingly well into our startup's deject-native Vue interface.
I tried to put the code up on GitHub simply it wouldn't let me upload a 10gb repository (and that was without our proprietary fork of mysql :)
Too much snark.
We are running an enterprise-scale Angular xiii "SPA" that blows the prior platform out of the water.
Information technology simply depends on the team and the goal.