Solid.js feels like what I always wanted React to be
typeofnan.dev
typeofnan.dev
Solid is nice and _seems_ to fix the issues with hooks, but as another comment mentioned, the challenge is with building at scale. It's unclear to me how this scales and where the sharp edges are.
React IMO trades off performance in exchange for ergonomics. These ergonomics bear fruit early on, but you start dealing with this debt very quickly. As "nice" as Redux is, I shouldn't need it so early. React is designed in a way that results in pretty terrible performance. I once wrote a React app, and discovered perf issues 2 weeks in. Any UI framework I used in the past would have scaled beyond this point without having to have the data layer rewritten. Frameworks of the past also had what seemed like way less "magic".
I totally accept that it's seriously nice to write, but how many trees has React alone burnt?
Edit: after writing this I went and read the article. Same scenario I was bitching about lol
React was easy coming from jQuery, Backbone other frameworks at the time.
With effects, i've read the docs many times. I still don't fully understand how it's supposed to work.
I don't seem to get the feeling / abstract concept behind it and it still surprises me at times when it fires / or not.
Too much magic for me. But maybe im getting old :).
The main issue is that it's not a native language construct, but a mini-dsl sort of so you need to have this state machine in mind even thought it's implicit and hidden from you.
Instead of reading the docs, you might want to search online how to write hooks from scratch. It's one of those concepts that needs to click.
In contrast, useEffect() is "exactly what I want" without having to figure out what combination of lifecycle methods to implement.
I'll grant you that this could have been done differently - I'm not a fan of the "order of calls represents hidden state" mechanism for hooks. It's possible to imagine a different API for class components that provides ergonomics similar to useEffect() and useState(). But hooks are still an improvement over the old class component API.
I've built some really complex frontends with React. But now here I was, struggling with setInterval, ha.
I would argue that the real footgun with hooks is the case where a `useEffect` call inadvertently gets triggered on each render because one of its dependencies, passed through another hook, changes identity on each render. It can get quite maddening, and in many cases you don't notice it until someone points out the resulting performance issue with your app. The solution, of course, is `useMemo` and `useCallback`, but it's not intuitive and it can be easy to miss from time to time in a large project.
useEffect(() => {
const interval = setInterval(() => {
// whatever
}, 1000)
return () => {
clearInterval(interval);
}
}, [])Took me at half a week at least and I felt like a god after. Then I realized this was all phenomenal waste of time and I decided my next job was going to be cloud and backend focused. Only in the js world can you realize immediately as soon as your done that it's effectively worthless programming hassle.
That said, I still preferred React.createClass so I guess I'm somewhat off the beaten path when it comes to React.
My take is that if a feature requires a linter to be properly implemented then it's obviously giving the developer too much rope to hang themselves with.
Also it appears that they were introduced mainly for performance, but for some reason sold as the new "better" way of writing applications.
I actively avoid React and its ecosystem, because I believe there's just too much FOMO and "fashion"(for lack of a better word) in what drives its development and not enough meritocracy.
> If a linter is required to tell me when I'm writing a bug that is not immediately obvious, that is a failing in the framework
yep. They also commandeered the entire use* namespace just so they could get lint to warn when you put a hook outside the start of a function. Hacks on top of hacks.
I still like using them however. I had a few issues when trying to do more abstract code.
They are highly, deliberately, emphatically procedural.
The order they are called matters! The time of when they are called matters! The number of times they are called matters! You get a different result from calling the same hook with the same arguments at different times! You get different results if the call site for them is in different places!
They do enable you to do some things in JavaScript that are more easily enabled with higher ordered function stuff in functional languages, but there is nothing ‘functional’ about how hooks work or how they are used.
And that’s okay! ‘Functional’ doesn’t automatically mean ‘better’ and ‘procedural’ doesn’t mean ‘worse’. For what they do, hooks (considered as the entire hooks ecosystem including linting extensions that help enforce the rules as if they were syntax errors) are a very clever extension within JavaScript syntax that let you pull off some very neat separation of concerns in a reactive code model.
‘Functionalness’ has very little to do with whether hooks are good or bad.
Because when function components first came along that's what the whole of React was supposed to be: "functional" UI, using things like redux or mobx for state. Plenty of guides still use that terminology even though React's homepage now uses "declarative".
That said I think they were always misusing the term, I remember this because I used to complain to people that react itself was declarative, not functional, and just gave the option of writing in a functional style.
The right way to do that exists in Elm. But I do not think there is a way to translate that into JS without requiring either a lot of boilerplate or very messy code
I've been working on a quite complex React codebase for 5 years now - it's not the biggest but still not so small. I was there on day 1. The team that works on it now full time is ~15 devs + 10-15 doing some minor stuff from time to time.
We've started using hooks about 1 year after they introduced them. Before we were very deep into redux and redux-saga. Now most of our codebase uses only hooks for most of the things we did with redux before - there are still some redux but most major parts are migrated to using hooks and contexts. It is probably the best decision we made after switching to TS. Most of our codebase is still very easy to maintain. Last year I went on a paternity leave for 6 months and I was pleasantly surprised how easy it was to adapt back.
Edit: forgot to write about Elm. I like elm a lot -even though I don't agree with how it's managed-. I even organized a local elm meetup :) But I think while it is very good in theory, it's not too easy to scale especially if you plan on hiring more devs. Also the way effects and data is completely separated from the view is not very ideal for bigger projects. You either end up having to touch too many files for a single feature or have incredibly big files.
There are other ways to achieve similar. You don't end up with "big mess of hard-to-follow spaghetti code", you might end up with a "large amount of unfamiliar-looking code". Getting better at reading a larger-than-anticipated amount of unfamiliar code takes a bit of practice, then it isn't a problem. And then you have all the benefits of Elm with zero problems.
The actual hard thing about code is managing complexity, and working with "it just works" magic when it doesn't "just work".
I agree Elm has some flaws, and there is an initial up-front time investment which is unsavoury to many.
If you compare this to Halogen (https://github.com/purescript-halogen/purescript-halogen/blo...) where you still have purity but can set up subscribers and listeners from any component. It's much easier to use and for some components like dialogs, it's much simpler. And this actually isn't the best example because with the latest Halogen, Portals (https://github.com/purescript-halogen/purescript-halogen/pul...) was introduced so you can launch a dialog on the spot instead of even needing to communicate between them at all.
This is my anecdote though. And I've been away from Elm long enough now (around 1.5 years) that I've forgotten all the specifics.
Those linter warnings with React hooks show just how much of a disaster it is. All of the "simplicity" that comes with hooks is just complexity that is now completely out of sight, and only appears once the code is run in a linter. That is even worse than having the complexity in the code.
On the JS/TS planet there's https://cycle.js.org , which comes close.
Looks even better than Solid IMHO.
You can write really performant software in React, but ergonomic (beyond stockholm syndrome) I would not call it.
It's also difficult to implement quality software engineering principles in a React application such that an application is maintainable, glacable and easy for someone new to a project to pick up.
The flexibility in its toolchain is nice, however
I do not want this handled at the framework level though. There are plenty of times in my day-to-day where that linter is wrong. If I were to add one of the dependencies (it's sure I should add) my component would re-render over and over. Sure, one could argue, "well, then you've poorly architected your code"... but THAT is where I feel like the failure occurs. Having to do write my code to please a paradigm. What that means is I only "sorta agree" with the design trade-offs. And much like Ruby on Rails, you either go all in, or spend your days hating the framework.
I do worry that Solid also has these "If you know, you know" edges though. So I'm trading looking at a function and assuming it'll run over and over with, looking at a function and thinking, "how can I make this thing run again when it needs to?" I'm not saying it's wrong, it's just another piece of tacit knowledge one has to learn when adopting a new framework.
If I know I have a dependency I want to ignore, to achieve a certain result. Then I have a way to achieve a particular data flow. One can _say_, that's wrong but it's a deterministic way to achieve that result. Calling it "wrong" delves into the weirdness of hooks. Love them or hate them, they create patterns which must be learned and mastered. And even then... they can still be confusing. Except for on the internet obviously, here we find people who never have problems with them :)
Isn't the point of static analysis (including linters) that they catch those kind of bugs? Having that little red underline (or console warning) saves a lot of pain.
Hooks have completely changed the way I write React code. It's so much easier to test and reason about. Really the only problem is that the guardrails aren't more heavily enforced.
Hooks are a syntactic element of react code. Calls to them aren't legal inside conditionals or loops.
Full linting support smooths over that rough edge just as effectively as babel handling ?. syntax smooths over its absence in certain JS runtimes.
Can you branch on state or use loops over data in Solid.js? The reason _why_ React has a virtual DOM is to enable more interesting relationships between your data and your presentation. Anyone can make a framework that makes the source code for an incrementing number look pretty!
As an example of this point, check out the "Simple Todos" example for Solid.js[1].
In React, we render lists by using regular JavaScript idioms like loops, arrays, and array methods like map. However in Solid.js, much like traditional templating languages, we get a construct like <For> that reinvents a concept that's already in the language.
I've been writing React and React-alike code for a long time. I think that fine-grained updates avoiding reconciliation are a good idea, especially for performance. At one point, I built a React-like library for Roblox and Lua whose most novel feature ended up being "Bindings"[2], which look sorta like Solid.js state containers. They create little hot-path data dependencies, but the bulk of your components still use normal React-like rendering.
[1]: https://www.solidjs.com/examples/todos
[2]: https://roblox.github.io/roact/advanced/bindings-and-refs/Isn't this optional? Can't Solid use regular JSX loops?
For reactive control flow to be performant, we have to control how elements are created. For example, with lists, a simple map is inefficient as it always maps the entire array.
This means helper functions.
I don’t see the big deal here. Error boundaries, suspense, context, very popular routing libraries all have used components to encapsulate functionality. That’s to say first party and third party functionality in the React ecosystem have gone down this path.
From the moment I saw a post about immer.js, I was sold because it seemed like an obviously better solution for the vast majority of cases where I would otherwise grab Immutable.js, a library that I wanted to like but inevitably struggled against.
This.. isn't quite as revelatory. I'm not saying it's not all that you claim it is, it's just that from a glance, I don't see how this somewhat different approach addresses the problems I run into often with React in a major way (beyond the claimed performance boost).
We have found that continuing to use immutable.js Map and List but using plain JS objects, not Records is sort-of a sweat spot. But one needs to enforce immutability with Flow/TypeScript read-only types and use the latest immutable.JS to make it work.
So, what you have here does not remove complexity from problems, it moves the complexity from one place to another.
So, when you have a simple task, and a straightforward framework, what you see is “it’s easy!”. …because when you use the complex framework you get a bunch of “solutions” to problems that don’t exist on your problem.
That’s why it appears overly complex.
…but for a complex problem, when all you have is a simple framework (like <For…>) you have to implement the complexity yourself, which makes you view the framework as feeble and under whelming.
So, you are just moving the complexity from one place to another; the question is, is the complexity of react really something most people need, or can a framework like solid solve the 90% of simple problems most developers have?
It’s hard to tell.
Most new frameworks excel at solving simple problems because it makes for cute demos.
Is solid any different?
That’s my question. How does it work at scale, for large complex projects? Is there a whole design system implemented in it? Who’s using it and for what?
The claim that it’s “not complex” doesn’t help.
All that means is there are probably a crap load of things it doesn’t include I’ll have to do myself.
There is no magic bullet that removes complexity from tasks.
React is a complex beast, and a nice clean framework to replace it would be welcome.
…but you have to approach this kind of discussion honestly.
Hello world examples are a dime a dozen.
I wonder if I could have your opinion on my library, and why half the code, native performance is actually more complicated in the long-run. I don't know the answer at the moment. Documentation isn't complete... it is just web components. eg hello world just becomes a function like const component = hello('Andrew'); document.body.append(component); in the example on github. Anyway, the todo shows a more typical real world example I guess.
Once you deal with larger amounts of data and need virtualised rather than fully-materialised lists, you start using different things in React as well. The fact of the matter is that if you care about performance at all, the simple ways are just insufficient, and the native language constructs were designed for procedural programming, not reactive interface rendering, which requires fundamentally incompatible semantics. It’s not even fair to claim that React uses regular JavaScript idioms—VDOM, hooks, the entire shebang is all about eschewing regular JavaScript idioms because they don’t scale. (OK, so there’s also the matter of transient state like scroll positions, element focus, and form field values; it’s not fair to say that React does all these things purely for performance’s sake, as the naive immediate mode approach would also break such functionality.)
For the UI part of it: what I would use would depend on my requirements (is it a list, is it a grid, how is it to be interacted with, &c.) and what was already in use (React, Svelte, plain JavaScript, other). I personally would often be inclined to implement it from scratch, because I’m typically not impressed with most library options (they have a tendency to be heavy, limited, and slower than they need to be) and am familiar with exactly what needs to go into it to make it as perfect as is possible (it’s not a particularly large amount of work, but it is fiddly in places and must be done correctly or it’ll be awful), but that’s not a course of action I would recommend for most developers.
My specific use case is a React application, and I have found it easier to implement a dedicated listener system, than try to fit things into component states.
I want to push back somewhat on this practice. Our computers are fast enough now, and the browser implementations optimized enough, that they should be able to handle thousands of materialized list items without breaking a sweat. Sometimes you really need virtualization, e.g. if the underlying data source has millions of records. But if the data can be fully materialized, then the implementation is simpler, and the user can take advantage of things like find in page. Virtualization is a convenient way to avoid the inefficiency of unoptimized VDOM-based rendering (e.g. with React, and yes, I know there are other optimizations available in React), but fine-grained updating (as in Solid) is even better.
It depends a little on the complexity of the rendering for each item, and where you are fetching the data from, but when you’re into thousands of records you’re very likely to need at least some partial rendering. Suppose each record’s data is one kilobyte (I’ve seen far lower and far higher), then one thousand records is already one megabyte, which for many people will take multiple seconds to transfer, so you’ll still want to load the visible records before fetching more, or do streaming parsing of the records as they come in. And that’s ignoring the backend’s performance on fetching records, which must be taken into account too.
People are certainly often too eager to reach for virtualised lists, or worse still lazy loading without reserved scroll height, but even at a thousand records with simple rendering they’re still probably generally warranted—fast computers can cope with comparatively little visible difference, but on slower ones (especially older and cheaper phones) you’ll easily feel the difference. Memory usage can also be a concern for larger quantities of data and DOM (1000 × 100KB = 100MB).
I’m saying all this as one that scorns React and VDOM stuff in general as unnecessary performance overhead, and likes to use Svelte and plain JavaScript and things like that (or better still, to eschew JavaScript); and who worked on Fastmail’s webmail, which certainly uses such progressive-loading lists, on a precise-DOM-updates framework that cares significantly about runtime performance. React and its ilk are certainly particularly prone to using virtualised lists as a crutch to work around their shortcomings.
All that being said: yeah, I wish things like Discourse would stop doing aggressively lazy loading when there aren’t even several hundred comments in a thread. Render just the things on screen to begin with, if you must (though it’d be better to just send real HTML from the server and let the browser take care of all this, even if it complicates your JavaScript loading), but then load all the rest straight away so that I’m not penalised just because I’m on the other side of the world from the server, and let the browser handle in-page search.
Speaking of both Discourse and screen readers, before my stint at Microsoft, I wrote a Windows screen reader, which tried to detect client-side page navigation by watching for the URL (minus the fragment) to change. Discourse's infinite scrolling implementation broke this heuristic, because Discourse would use the history API to update the URL as the user scrolled. Not sure if I or they were in the wrong there.
Interesting that you feel that Discourse penalizes you for being far away from the origin server. When Discourse was new, one of the founders blogged about how their heavy use of client-side JavaScript made the application better for users far away from the origin server:
https://eviltrout.com/2013/01/06/turbolinks-and-the-prague-e...
Maybe the author had a point, but it sounds like Discourse still relies too much on frequent round trips.
Edit to add:
> a precise-DOM-updates framework that cares significantly about runtime performance
That's Overture, right? I wonder how it compares to Svelte and Solid.
I find this a totally bizarre complaint. I've spent the past few months working on Svelte stuff and I've seen people on HN make this same complaint about Svelte's templating language with {#if} and {#each}. Who cares? What is so wrong, exactly, with "reinventing a concept that's already in the language"? It does not make code any harder to understand or to write, and it does not harm performance (in this case, quite the opposite).
I would much rather have a reactivity model where I plug in completely standard concepts and patterns (a for loop) than one where I have to deal with a bunch of framework-specific, complicated ones (hooks). That Solid's reactivity primitives are familiar is an advantage, not a disadvantage.
Personally I've never found a problem I wasn't able to solve in Svelte.
So you end up with a secondary full featured language usually with worse IDE support, worse error messages, more surprising issues, etc. You need to understand the scoping mecanisms and if things go wrong hope there is a debug tool available.
And in the end those templating languages do not prevent you from mixing UI responsibilities from the rest of your code.
If you want a reactive model you can have one. I personally prefer explicit messages like calling setState.
The idea that this type of thing should be happening anywhere near the view rendering loop is the exact reason I've not had a great time picking up React codebases.
By the time you're rendering data into markup, the data should be in the exact state you need it. No further filtering or data mangling or sorting. That type of data manipulation should happen at the point of data change and then it shouldn't happen again until the data changes again.
The simplistic templating languages in Vue/Svelte/Alpine/whatever-comes-next force you to pull your data manipulation back to somewhere more appropriate, with Vue even throwing a warning if you try to filter within v-for construct.
Because React is JS, people are let loose to do wildly inefficient operations and do them over and over and over whenever _anything_ in that component changes.
It’s nice to have a concept “ground truth” in data and props and then computeds that sort of tie it all together.
You can do same/similar with React hooks, just not as clean or obvious.
I do, however, think that working with React changes your mental model somewhat, and when I'm working with React I catch myself doing a lot more data wrangling close or in the rendering loop than I would in any other modern framework. Certainly since class components have fallen out of favour, you're working with a function designed to be run hundreds of times, while Vue and Svelte both provide clear patterns to deal with data at the point of change, then separately deal with updating the display of that data as required.
It takes using something like MobX to really push a React codebase to a data-driven model and that means many inexperienced developers fall into the common pitfalls far more easily than if they're using an alternative framework imo.
Gilad Bracha calls these "shadow worlds" https://gbracha.blogspot.com/2014/09/a-domain-of-shadows.htm...
Having templating DSLs in other frameworks isn't a deal breaker, but it's a pro of React that I appreciate.
Well, what can you tell me about TypeScript type inference for this custom DSL?
Nothing, inherently. Just like there's nothing inherently wrong with having extremely clear and simple rules for how to use hooks, and lint rules to identify when you're not following those rules. Nothing inherently wrong with either, some people just have strong distaste for one or the other.
Actually, that is only half the reason. You can do whatever you want in my library (github.com/thebinarysearchtree/artwork) and it doesn't have any kind of virtual DOM or whatever Lit does, because you just create elements with JavaScript. The second reason, that everyone just assumes is the default, is that React has to use HTML-like templates and not just JavaScript.
I'm right there with you, but when React invents a whole markup language inside of JavaScript, it's not in much of a standing to make purity criticisms.
It has no intrinsic semantics, and maps pretty much directly to actual javascript (which you can write directly or use an alternative helper for — hyperscript being a common one).
It's about as pure as you can get while having any sort of html-ish 'templating' whatsoever.
So, I'd say it's exactly in the right place to be making purity criticisms. They've taken the only approach that preserves the integrity of the code and doesn't involve build time magic.
But coming back to JSX, a custom function call syntax is OK and pure because it has a one to one mapping on line number?
I don't know if there's much point in discussing purity since it's badly defined and mostly in the eyes of the beholder, but it always smelled like one hacky syntactic sugar to me.
function MyComponent() {
return For({
each: [1,2,3,4],
children: x => <div>{x}</div>,
})
)
It's just a function call, and it doesn't even need `React.createElement`. What's more pure than that?What I like about the React monoculture is that it's one less thing I have to care about. I can focus on the other aspects of my programs, beyond turning JSON into HTML.
I haven't used SolidJS so I'm not going to put it on blast. However, hearing people compare its reactivity model to Knockout JS gives me the heebie-jeebies, because Knockout projects were horrific to reason about (and test) beyond a certain scale.
This argument is silly because it inevitably becomes a pissing contest of who can be most like vanilla JavaScript. In that case, why use JSX? Just write hyperscript calls instead. Why use React Router/React Context helpers? Just wrap your components using vanilla function providers instead. Why use React Hooks, which inevitably look like magic to a JavaScript veteran because the library inherently hides away some global state? I hope you can see what I'm getting at here.
I had/have your bias, but from playing with it I found a couple things:
1) Like React, you can swap out the template feature for a function call (or subcomponent). e.g. instead of
return (
<button...>
...
</button>
<For each={state.todos}>
...
);
you can use functions and loops: function displayTODOs<T>(todos: T[]): any {
let arr: any[] = [];
for(let [i, todo] of todos.entries()) {
const { done, title } = todo;
let elem = (/\* JSX \*/);
arr.push(elem);
}
return arr;
}
...
return (
<button ...>
</button>
{displayTODOs(state.todos)}
);
2) Even with my bias, I must admit I found the `<For...` syntax to be surprisingly easy to read and fast to eye-parse; much more so than other 'templating' (using your term) languages/macros/syntax I've used over the years.That said, I think that easily the most difficult aspects of react revolve around how re-renders are triggered. Maintaining referential equality to stop unnecessary renders gets tricky when you are passing functions or objects. Suddenly you need to be using `useMemo` and `useCallback` and passing dependency lists that all have to be primitive values unless you want to memoize them as well. It can become such a headache that the official line around it mostly seems to be "make the render fast, don't worry about unnecessary re-renders" – good advice, until you hit a use-case where you need to worry.
Solid takes these problems and just vanishes them. UI state knows what its dependencies are automatically and only updates when they change – even in a sub-component level!
To be fair, I've never used Solid in anger, and moving to it would be a big ask when there is such a good ecosystem built up around react. That said it is easily one of the most exciting projects on my radar, and the developer Ryan Carniato seems extremely knowledgeable in the area.
https://english.stackexchange.com/questions/30939/is-used-in...
How is grok considered hacker lingo? I would think other people than hackers have read Stranger in a Strange Land.
But then again even by british standards I am unusually sweary when writing code.
What React has going for it, is that it is predictable. That is an extremely important part of any tool.
I haven't looked at Solid but I've used MobX extensively, and this sounds a whole lot like it. It integrates well with React, so you might give it a look if you've got an existing React codebase.
The only thing it doesn't obviously do better is the JSON Patch generation stuff that I get from mobx-state-tree and I use the word obviously because it would not at all to surprise me to discover that solid already does that and I simply didn't RTFM hard enough yet.
The sheer level of ecosystem (and the "nobody ever got fired for" advantage that results) may keep me using react but solid is a bloody impressive piece of kit and whether I ever end up using it myself or not, "bravo, sir" applies.
> "Ohhh, an OO pattern with a couple of one-liner lifecycle methods is just WAY too much code! Higher likelihood for errors and worse developer experience."
...
> "So instead, I'm going to replace this with a functional pattern, that crams a couple of lifecycle functions into a closure, and is riddled with edge cases and common developer mistakes."
This article perfectly crystalizes why my career has tracked toward the backend over the past decade. All of the virtual ink in this article, and honestly most of the complexity in the field overall... and it seems to really all just boil down to, "I think this looks cooler."
In my experience, backend development is often simpler because you can move any state out of your own code into dedicated external components, like databases and queues. With frontend code, you have to manage state; there’s nowhere else for it to go.
IMO there's significant complexity in building a feature-rich frontend client. The "thicker" the client, the worse it gets. There's definitely a lot of 'I think this looks cooler' going around, but also we shouldn't forget that the need to come up with something better is partially a response to very real, very-not-imagined, frontend complexity.
Doing complex things is always complex, but when SIMPLE things are complex, then something is going very wrong.
And this is exactly where we are with most JS frameworks these days. Layer upon Layer of abstraction, and instead of the complexity the dev has to deal with decreasing as a result of it being abstracted into frameworks offering simple interfaces, complexity increases.
Have you been saying the same thing since 2014? JS frameworks have never been simpler, never been more discoverable thanks to TS, and there are plenty of levels of abstraction a developer can put between themselves and vanilla JS. But even calling React too-far-abstracted-to-be-simple is comical; it's a simple system offering composition of components.
I think if you actually used hooks, you'll notice this immediately. It's not a matter of "looking cooler", a lot of language theory went into making UI development functional and less stateful, which in turn makes it far easier to manage complex applications. A small team can maintain a pretty huge beast if using hooks effectively.
Everyone always likes to blame the front-end engineers for being slovenly, but my experience is that; UI is just messy. It's just hard to program cleanly.
Not to mention, modern UIs are generally more complex than the old VB days (at least, my programs are): they have to adjust to various screen sizes. They are almost always client/server apps and need to account for more failure modes. They are built on top of a mess of a document layer that was never intended to be an application layer.
This last point is the reason the front-end space has so much churn. It's still an unsolved problem, and may never be well-solved, but I'm glad folks are trying to solve it. React was a step-change for me in terms of building better UIs. I'm looking forward to the next step-change.
Lastly, before someone makes the argument: no; we aren't going to stop building applications on top of the DOM + CSS. Not until someone comes up with an alternative that gives us the same ease of distribution and broad base adoption.
Edit: I should note, I'm a full-stack dev, and have been more back-end than front-end for most of the early part of my career. The backend is always easier for me at least, but I don't think it's because front-end devs are hipsters.
I'm an almost entirely frontend dev (iOS + macOS now, web development in the past) and this is what I've come to believe. It's easy to program UI cleanly if it's extremely basic or not very usable — but the second you want an animated transition between states, or to remember what the user checked on the last page so that you can keep it checked on this page, or any number of other things that you need to do if you actually want people to _enjoy using your software_, it gets much harder.
My take is it's because building UI is building software for humans, and humans often want behavior that doesn't allow for clean abstraction. Backend dev is more about building for other software -- not that it's easier, just a different set of problems.
Never really thought about it this way but I completely agree
In a way I find this meme even funnier now because of how backwards it is. Often times it's the backend that's really clean and organized and the frontend is a hot mess.
You're using this straw man to demean the author, but I think you miss an interesting point: it can be very hard in software developer to articulate the good and bad. "Uncle Bob" refers to this as "code smells", where you can't quite say immediately what's wrong here, just that you don't like it much. Something smells bad.
And maybe the point of Solid is to point out a mistake React made in their implementation of hooks. Hooks were badly needed, no doubt, but often times an okay solution to a really serious problem can look like a great solution.
The back end went through a lot of this already. That's why the patterns are more stable there, and why you feel less churn. The front end is exciting precisely because there's so much to still figure out!
To people who know what they are doing more code than necessary to accomplish a task is the code smell.
To people who are super insecure vanity code is required because patterns are memorized, so any deviation from the unnecessary boilerplate is the code smell.
While I agree, I think a lot of developers are oversensitive to boilerplate, sometimes to their own detriment. And the effort to shave off boilerplate quickly runs into diminishing returns. Beyond a certain point you end up with code that is harder to use because of the layers of abstraction you've added to avoid the last-mile developer writing unnecessary boilerplate.
But I am a touch typist, whereas I'm noticing more and more developers who are not, so maybe there's something there.
UI developers focus on user interface, and much of that has to do with looks, style, and personal ergonomics. In a way, it makes sense that the engineers steeped in this type of problem set would be oriented to thinking this way. Even if they aren't initially, the probably will be over time.
react isn't about 'hooks', 'jsx', 'top-down-state', or 'component-driven architecture'. All these frameworks are component-based, can have top down state only (or do bottom up in react), can use things like jsx/hooks because it's just syntactic sugar (vue has jsx support).
react is fundamentally about 'inputs changed, render this'. This got rid of a lot of issues with poor code because frameworks had crappy DX (angluar 1 scope nonsense, and overengineered DI concepts), and people were bad at tracking side effects because a lot of people just wanted a search bar with some cool features and not everyone was building sophisticated products.
That setInterval example is fundamentally against what react is, and is basically svelte/vue/(react + mobx).
Vue/svelte/solid do not fight against js, hence they do not end up in similar situation
SolidJS splits it between <For> and <Index>. <For> is equivalent to passing the object as the key and <Index> is equivalent to passing the index as the key.
https://www.solidjs.com/tutorial/flow_for https://www.solidjs.com/tutorial/flow_index
That's one of the design decisions I don't fully understand. It knows that there should be a key there so why just not put it there silently and let me override it when I need, instead of screaming at me when I omit it.
Could it silence the warning? Yes. However, the React devs choose not to. I think it’s the correct default, but likely needs a more educational warning message.
And it also goes into why index is a poor key (it's basically the same behavior as with no key).
Using object identity to detect inserts doesn't work either, because the map function is returning new React element objects on each render.
Practically speaking if you know your items won't change, then omitting the key or using index is fine.
Don't omit the key in React unless you want warnings.
... you can add a new ID property to your model or hash some parts of the content to generate a key.
It is just plain wrong to ask me to change my data model because of this. This is part of the housekeeping that I expect the framework -- pardon, library -- to take care of for me.
Now this does require special process for intaking immutable or big data snapshots where we can't do reference comparison. So we do have a data diffing capability in our nested reactive stores to propagate only what changes. But for the most part common actions like partial updates highly optimized. As well as simple list operations like sorting.
With React, "plain JS" works just like I expect it to. If I have an event handler that does `x = foo` then I don't expect my component to re-render. Why should it? I'm just changing the value of a local variable. If I want to re-render, there's no way to express that in plain JS, so I'll use React's API and write `setX(foo)` instead. Now it's clear that it's not just changing the value of a local variable, but using React's API to do something else.
With Svelte, writing `x = foo` doesn't just change the value of a local variable. Maybe it's going to run a bunch of magic to update a piece of the DOM instead. Or maybe I need to prefix it with `$: ` which in plain JS is a label for a continue or break statement, but here doesn't mean that at all and means reactivity instead.
Oh, and to conditionally render an element, instead of writing idiomatic JS like `condition && <Element />`, I now have to write `{#if condition} <Element /> {/if}`.
WTF. What looks like plain JS is now magic, and what should look like plain JS such as conditional rendering and lists are now some contrived templating constructs.
And almost everyone here is telling me that I should find that simpler somehow.
It makes zero sense.
Especially when I compare it to Svelte and Vue (not solid, solid.js is just... good), if I look at a component, with react it's way easier to say what's going to happen.
Aren't there gotchas? Yes, but sometimes it's just stuff JS lacks, and so does React.
I'm very excited about Records and Tuples in JS to help with the immutability, for example: https://github.com/tc39/proposal-record-tuple
React is unique in that everything in the component is within the render path, while the rest of the frameworks (that you've mentioned) doesn't.
you might be mistaking "side effects during render is bad" for "side effects is bad", the two statements are not the same.
React’s philosophy is View = F(data)
I.e. view is a pure function of data. By “pure”, we mean F() does not do console.log, ajax calls, date time and other stuff which is not consistent every where.
This assumption is ingrained in React. You see it when you are told that react can overrender and your code should handle overrendering. And react works well when user code is pure. However, real world does not work that way. So, there is a need to handle side effects, so that “side effects” works well with pure function assumption of react. This “handling of side effects” is the over head introduced by react.
Other js frameworks (svelte, solid, vue) do not assume full immutability or pure functions, hence User code does not need special handling for these cases
That's just how templates are meant to work. Underscore.js templates don't allow making an AJAX call before calling render() either. https://underscorejs.org/#template
User is entering an account register form. When the user has entered a value in nickname, your app must check if it is in use and display error message if the nickname is already in use.
Sounds good, and ubiquitous right? Well, that also require an ajax call to server for validation, so it breaks the pure function assumption right there. Now, you what do you do?
When you display the error message, yes, React provides a way to do that without re-rendering the input box and while keeping the contents, but many react devs are skipping the traditional React way of doing that and using react-hook-form instead.
I get what you're saying about the component's data updating the state of the DOM in a way that resembles pure functions, but I think AngularJS did it before React, and that Backbone was not far from this vision. Certainly there are a zillion JavaScript frameworks that do this now, and only React has you jumping through silly hoops like "className" and "htmlFor". https://preactjs.com/guide/v10/differences-to-react/#raw-htm... https://www.solidjs.com/tutorial/bindings_classlist
There's no pure function assumption being broken here. React is a framework for rendering UI from state and coordinating updates to that state. That's why we have things like `useEffect`, contexts, and so on. The only part of React that is expected to be free of side effects is rendering.
Put another way, given your example, React just says that you shouldn't issue your Ajax call in your rendering code. Instead, you should do it in response to an appropriate action, such as a change event on your form controls.
Yeah internal component state throws all of that out the window.
That's lit-htmls philosophy, not react. React is all about bundling the view and state and then marathon profiling sessions to figure out why everything is re-rendering all the time.
The transition to functional components was to reduce the coupling between abstract functionality and DOM-related lifecycle events.
React hooks are mostly about expressing where and when you want to memoize a value, with the default being not to.
Once you learn what to look out for, and properly designing and review codebases at scale, these trivial issues don't happen all that often. Additionally, being able to specify memoization parameters explicitly brings extra flexibility and some additional design patterns.
https://reactjs.org/docs/hooks-faq.html#what-can-i-do-if-my-...
That was really my point, don't do that.
For example a flurry of setStates could be wrapped up in one single state. If it gets too complex - into a reducer.
Components that don’t benefit much from splitting up could have their business logic wrapped into a context, and let the view code be just jsx without all the interweaving of code and templates.
Maybe the one benefit of classes was like it forced you to think in business logic, then render. React still has that, you just need to dive a bit deeper into its toolbox.
The result usually turns out much more flexible - contexts neatly wrap business logic for all of its descendants, classes don’t.
I think this was maybe because react actually allows you to write messy code, and it’s still performant and works. But in the end it just kinda postpones the inevitable maintenance burden.
I guess solid.js from the looks of it might postpone it a bit more. I just worry that solid looks more like magic, and some invariant somewhere will just break and I wouldn’t know what sequence of reactions actually led to that infinite loop that crashed the page. Haven’t tried it myself though, might more understandable in the end…
You've just deoptimized your app, and your whole component will re-render on every change.
> Components that don’t benefit much from splitting up could have their business logic wrapped into a context
You did it again. More unnecessary re-renders.
> it’s still performant and works
True that 'it works', but it's usually not as performant as you think - we just have really fast computers and phones now.
There's a parallel here to "no, you did not find a bug in the compiler". Yes, ok, once every five years or so I actually did find a bug in the compiler, but assuming you aren't that smart is still a far far better default approach.
On top of that, profiling and optimizing a real world application with a dozen hooks in every component is pretty painful.
If you have 3 useState each of those will use 3 useReducer internally (every hook is implemented on top of useReducer), If you consolidate them into one useReducer then you will end up with the same thing performance wise. Maybe even better. Whenever an event is pushed into the hook's queue it marks the component as dirty. The next call to useReducer will then reduce all unprocessed events into the current state. It's entirely possible that having less hooks and therefore less metadata in the background can improve performance more than avoiding the theoretical cost of rerendering a component that most likely would have to be rerendered anyway.
But you certainly are correct that useState is reducer based. I'm pretty sure one is only avoiding rerender via using multiple `useState` if they don't implement the reducer in a way where it returns the original object when there was no net change. If you are able to implement the such that it only returns a new object when there really is a change, then a single useReducer call is strictly more efficient than multiple useStates. (This might require more complicated code, as returning a new object every time is often the easy way to implement reducers.)
It’s understandable to stumble into this difficulty though, and a bit of deceptive marketing on the part of the hooks folks. They should be upfront that using hooks well in a real app requires a lot of careful thinking of the kind that many “typical” programmers do not have much practice in, and then the maintenance of whatever code comes from the effort. The functional-programming-mindshare situation seems to be improving slowly, but still.
If the lifecycle methods you're referring to are things like componentWillReceiveProps or getDerivedStateFromProps then the React blog covers why they were problematic https://reactjs.org/blog/2018/06/07/you-probably-dont-need-d.... It was very common for developers to make things that would repeatedly rerender when other parts of their app updated. Hooks make that far less likely to happen.
That said, I agree that a getDerivedStateFromProps method is more readable and much clearer than useEffect(()=>{ // stuff }, [big, list, of, props]);
when, as I often encounter, organizations mandate all hooks all the time they are not throwing the baby out with the bathwater, but they are maybe throwing out the baby's rubber duckie without considering that might be useful to have around at times.
The actual article acknowledges that when it's read: "React isn’t truly reactive."
And the author also claims to love React and to think it made things better.
You're arguing with phantoms.
I'm having a lot of fun lately using Kotlin-js for example. We use the Fritz2 framework, koin for dependency injection (popular on Android as well for good reasons), and fritz2 relies on kotlin's co-routines and StateFlow for state management. It makes for a surprisingly concise code base. For example, the counter example from the article with that would look something like this:
class CounterStore : RootStore<Int>(0) {
val koinCtx by lazy { GlobalContext.get() }
// handler that you can bind events to or invoke directly like below
val inc = handle { old -> old + 1 }
init {
// launch co-routine to keep on incrementing the counter
GlobalScope.launch {
while (true) {
inc()
delay(1000)
}
}
}
}
val koinCtx by lazy { GlobalContext.get() }
fun RenderContext.counterComponent() {
val counter by koinCtx.inject<CounterStore>()
h1 { +"A Counter" }
// react to changes in the counter
counter.data.render { currentCount ->
p {
+"Current count: $currentCount"
}
}
pushButton {
icon { arrowUp }
events {
clicks handledBy counter.inc
}
}
}
fun main() {
startKoin {
modules(
module {
single {
CounterStore()
}
})
}
render("#target") {
counterComponent()
}
}
There's a lot going on here that I can't explain here. But having co-routines means having a proper reactive framework that you use to react to events and update stores, which is where you keep your state. counter.data is a so-called StateFlow; the render function maps updates in that flow to the dom. In the example I have both a button and a co-routine updating the store via a handler lambda function.Using koin here, just means keeping glue code out of places where it doesn't belong. It's technically optional but makes a lot of sense in larger applications. Because components are extension functions on RenderContext, I use a global variable to get to the koin context. That allows me to inject my dependencies into components with a minimum of fuss. Where Fritz2 gets fun is with more complex state using data classes, lenses, validators, routers and a few other things. And they also take care of styled components and they even have a nice component framework that you can use. Not for everyone and there's a bit of overhead in terms of download size. But great if that less of a concern.
I can't begin to express how sad that makes me. Your component should have its own scope that it destroys when it gets destroyed, otherwise your coroutine leaks to the outside world when your component is gone from view.
I would not at all be surprised or troubled if, having studied it, you still dislike it, but there are definitely ideas in there that I consider to be at worst -interesting-.
If you have some recommendations or want to share your experience with working only with web standards I want to read them :)
Loads fast, easy to debug without tons of layers in the middle.
And yes, I also do manually make use of script and vendor JS libraries.
Naturally it only works when doing side gigs on my own, on big Web projects where my role is mostly BE/DevSecOps, I go with the flow.
Honestly, the boon of React is just how easy it is to create components, or at least how simple things were back in the day - it is exceedingly composable, moreso than AngularJS, Angular or Vue have been, at least in my experience. In React, your component can fit within a single file, containing simple syntax, especially for when you're making a pure functional component with no side effects or hooks. And even when you need to add something more complicated, you just have a method or two to change, essentially "progressive enhancement" for your code.
Though admittedly state management, or at least our current approaches to it ruin everything with endless boilerplate (Redux, Vuex etc.) to address an issue that may or may not be easier to represent, though some libraries certainly try (MobX comes to mind).
Of course, my experience leads me to agree with the article, in how React in combination of hooks sometimes is problematic, although in my case that was primarily because of render loops and how the stack traces are akin to JDK 8 NullPointerExceptions, where you couldn't see exactly what's causing you problems: https://blog.kronis.dev/everything%20is%20broken/modern-reac...
I'm probably wrong in liking class based components since those have other issues and Vue/Angular both feel a bit less productive in comparison, even if sometimes easier to reason about, with different tradeoffs to them. Maybe i should check out Svelte some day, but i guess it's all just one long slog of finding what works for you and what doesn't, much like it is with back end programming languages or even relational DBMSes.
It's really bizarre to me how poorly useContext works, in contrast to how good everything else in React is for the most part. Having a good, "official" global state management solution that requires little boilerplate would be a huge benefit.
There are enough different takes on how to state management that I am ... ambivalent ... about whether having a single official solution would in practice be better than the current situation. It's inevitably going to be a trade off and the react team not wanting to pull the trigger on such a thing until they're -really- sure is probably a good thing overall.
As a side note: I agree that useContext is weird, but jamming what (at least according to the mental model I use when working with it) is dynamic scoping into a language without native dynamic scope is probably always going to be at least somewhat weird.
Furthermore, a lambda local to a function can be a full-blown component (visible in DevTools etc.).
So if you need a component that is used in only one other component, you can neatly encapsulate it and make it invisible from the outside, which can be useful on occasion.
I mean, pretty much all frameworks these days have that fundamental declarative model, react wasn't particularly innovative on that front (e.g. the declarative model already existed in angular, knockout, etc)
What the setInterval example highlights is that newer subsystems in React like useEffect and Suspense are bolted on top of earlier iterations that weren't originally designed to support these kinds of semantics, and the dissonance between API design iterations has become noticeable. This is a pain point that is relatively unique to React.
The growing popularity of Svelte and Solid are largely because their API designs align naturally with how people expect features to work, without people falling into pits of failure like stale closures and incorrectly wired dependencies. React is popular and it puts bread on your table and all, but pretending it doesn't have warts doesn't do anybody any favors.
React was absolutely a breath of fresh air when it was released.
Knockout was similar to Solid.js in that they both have functions that you call which then log a data dependency, then when the data changes the UI updates. This led to lots of pain, because instead of a plain value, you have functions which return values, and you need to be very careful about when those functions are called, otherwise the data dependency might not be tracked properly.
Angular had a similar issue, as its state-based observation relied on special scopes. Updates in the wrong scope could be lost or delayed.
React’s approach of only diffing the rendered UI rather than trying to drive updates based on diffs of the input data was vastly simpler, it was much easier to understand the data flow through explicit state and props.
The phrase "an idea whose time had come" springs to mind.
(this comment is intended to read as professional respect, not fanboying - the extent to which I succeeded in that intension must inevitably be left as an exercise for the reader)
Very good.
IMHO, historically, the bigger pain point with the reactive model was data marshaling/unmarshaling (e.g. updating some subtree of data and then needing to send the root of the data tree to the server while maintaining reactive bindings across a large app and being careful not to fragment source of truth). Ironically, React can also end up in this predicament, because the encapsulation model of its `state` mechanism means extracting the actual state of the component tree is non trivial unless you're using a third party state lib to avoid it altogether in the first place, or at least use useReducer, which is a relatively new addition to React (and even then, it's kinda jank).
These days, React is a hodge podge of many different implementation approaches. Yes, there are props, but Context also exists - and is used extensively in the wild - precisely because props get clunky, and then there's data diffing happening to support `memo`, on top of the virtual dom change tracking. Suspense basically requires your code to adhere to semantic restrictions, i.e. you're not even in control of when your component function is called, which leads to having to tip-toe around that scope w/ extra closures, which in turn leads to all the issues that the article touches on.
The hodge podge issue isn't specific to React; Vue is also seeing pain points from having so many ways of doing things now that they're trying to push a v3 and realizing ecosystems tend to slog.
To your point, yes React was relatively simple when it came out, but as I mentioned, it wasn't the first to take a stab at the declarative model, nor the simplest. It just benefited greatly from the popularity wave of the golden years of Facebook OSS engineering. And from a practical perspective, it doesn't really matter what React was. Idiomatic usage is a thing, and React development today isn't like React development 7 years ago.
The 'inputs changed, render this' paradigm (and by this I mean reactivity, not the declarative model) has been around for much longer and is exactly what this post is about - React doesn't really do that, since it relies on you to explicitly tell it, via dependency arrays or setState calls, when to re-render. It is not fundamentally different from `.on('change', this.render)` code we were writing back in 2010, just a lot of syntax sugar on top.
That React managed to sell itself so well, while not actually delivering on the reactivity or performance promises, is the surprising part. I'm excited for the future as we finally move on from this era.
"React as Schelling Point" ?
Lit takes care of templating and reactivity. Web components don't have those, it's expected that you use other methods, including what you already use, to create DOM and react to state changes.
The DOM may eventually add templating and reactivity, but that's a pretty big question given how many approaches and syntaxes there are. Until then libraries are fine and allow for multiple opinions.
Just look here at how much overall code is needed to do it right: https://github.com/ing-bank/lion/blob/master/packages/input/...
After you get through all the inheritance and mixins it's thousands of lines
There are proposals for this and most of the other issues I have with web components. But they all feel like issues that could have been covered from the beginning.
Also if you go all Lit on an app with many nested shadow doms it becomes fairly painful to test with tools like cypress.
My point is that you were entirely wrong. Web Components are not ready for primetime, they are half baked. If they were the easiest and most pragmatic way possible to build web applications people would do so.
The only thing they are the easiest and most pragmatic for is to build a simple non-form associated component that can be used across frameworks. Like a card.
> It has always been a chore in one way or another.
It's actually never been a chore to make an <input> behave properly. Something that literally every component library needs to do.
Newer frameworks are absolutely better for anybody who isn't sufficiently batshit enough to do that, but much though I enjoy react + mobx (especially react + mobx-state-tree) I've never got to the "I have the core source code in my head and can mentally dry run it as a desk check type operation when debugging" stage with them like I did with early angular so - with the level of jank inherent in its scope nonsense entirely acknowledged - I still occasionally miss it even so.
(this is mostly me being nostalgic, I think, the newer stuff is absolutely better but that was a fun few evenings and for its era damn but I could make that thing sing)
Classes may have been more "code" but were clear to understand. I don't dispute that functional components are probably more efficient though.
Anyways, I've never had this problem with React hooks. I've been building complex dynamic UIs for years, and maybe I've grown to get around these kinds of things, but it seems like Solid.js is solving a niche problem at the cost of making hooks even less understandable?
I've tried using bare React in the past (after using Clojurescript), because I wanted my project to be more approachable for outsiders. But I couldn't really handle the (to me, and the author) unnecessary complexity that's added.
I would even say the Reagent version is even simpler than the Solid.js version, because you're using Clojure's Atom API rather than creating read / write functions. For the adventurous hearted I'd definitely recommend giving it a try!
Edit: Someone posted a Reagent counter example on codepen a few days ago: https://codepen.io/Prestance/pen/PoOdZQw
Having used Solidjs for some pet projects, I've come to strongly prefer Solidjs over React. It's an evolution of react, so I've found my existing skills/knowledge transfers. This being said, Solidjs is brand new and the ecosystem is minuscule compared to React. For this reason, I plan to continue using React for the foreseeable future. One of the biggest weaknesses of Solidjs is the lack of a "nextjs" like framework. It appears work is being done in the solid-start[1] repo, but it looks like it's still years away from being fleshed out. I want Solidjs to succeed, but I'm not interested in being an early adopter.
[1]: https://github.com/solidjs/solid-startI don't particularly like React, but this strikes me as the one thing it got right; the only "always correct" thing to do is to rebuild the VDOM on any change, so that's the default.
Then you can be more selective about which parts as performance dictates.
For all these reasons, while I do really love Solid's API, React + Nextjs + Vercel (or another React stack like Gatsby, etc) ultimately provides a smoother development experience for the time being. It isn't enough to build a better React, someone needs to provide an easy to use build and deployment process for it as well.
I ended up giving up on my Solidjs experiments because I spent too much time debugging the build process and porting React libraries. It's still not obvious to me how I could deploy a Solidjs app to, e.g., a Cloudflare Worker and provide a `/api` callable functions endpoint for the application. I have no doubt that I could figure all of it out, but I'm not interested in spending the significant amount of time necessary to do so. I love the fact that Nextjs just gives me all of this. All of this is to say that, while the core Solidjs library is really "solid" (pun intended), I still don't think Solidjs is ready for new projects (unless you really like doing things from scratch).
The chicken-and-egg ecosystem problem for new frameworks is tough. I've been working on Svelte stuff lately which has a similar problem but less extreme--the ecosystem is still much worse than React's, unsurprisingly, but it's also much better than Solid's right now.
I think Solid's primary branding is around performance and Svelte's primary branding is around it being easy. For getting things off the ground, I think "easy" is a much more successful approach.
Compare this to Svelte which has the goal of creating the perfect high level abstraction so that you never need to understand how things work and was originally created for smaller one off projects with much smaller complexity and no maintenance burden.
It's a little disheartening to see that it's 3+ years old and has only had a single significant contributor though[1].
It's impossible to avoid single-contributor projects in the JS world, especially with Node, but the alternatives (React, Vue, Angular, and even Svelte) are orders of magnitude more popular, so it's one area that we can play it safe if we need to.
But from what I hear, he's still pretty responsive on Github.
But things like the site, docs etc.. are much more contributors making more substantial submissions: https://github.com/solidjs/solid-site/graphs/contributors https://github.com/solidjs/solid-docs/graphs/contributors
We would have never gotten the docs translated into 15 languages otherwise. I do agree that one should be cautious regardless. But I don't want to underplay the contributions of many contributors putting in improvements every day.
I would hope that if either of us got hit by the proverbial bus that people involved in the ecosystem would pour themselves a strong drink and dig in to the necessary maintenance anyway.
Projects I've ended up moving on from have regularly worked out that way, and I think that while solid might not be as popular as some people would want for something to bet their production code on, it does seem to me that it's popular -enough- that I don't believe you're a truly dangerous single point of failure here.
(if this comment read as negative rather than an attempt at a clear eyed analysis, I apologise for phrasing it wrong)
In reality, you will never need to write an auto-incrementing counter :) React gives you 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 it's a little bit pointless to compare it with an auto-incrementing counter application, in reality has no use case at all.
This post helped hooks "click" for me, and once it did, I've absolutely loved them and now thoroughly enjoy writing custom hooks that greatly simplify my code.
the amount of confusing boilerplate I've seen to keep updated and maintained when a JS framework is loading front-end state by making API requests against a backend and then trying to figure out how to keep those in sync when we could just be firing off SSR HTML over the wire and/or very thin events that FE components can subscribe to or emit for literally no gain in functionality is beyond me
even better, just add reactive sprinkles over what you need reactive and do the rest with standard MVC/REST 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 chat channels...
In the -common- case OP seems to me to have a valid point.
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 done, and the more you try to overcome those limits the more you simply rebuild what is already available in the SPA side of things.
It's also inherently monolithic, meaning that if you want or need to support a mobile/native app for your public-facing app, you'll now need to develop a new "interface" (an API), when you should have already done that to enable the web app in the first place. Is it really worth skipping API/UI separation on day 1 when you know it's going to be needed on week 2?
You might say, it's fine, we're going to just make API calls for the Javascript, but then you've got an inconsistent availability of the functionality, and the second you hand that to another team to consume you will have wished you had simply built out all of the needed functionality directly in the API anyway.
It's not like having some frontend templating logic or reactive forms or whatever is going to actually be harder than just doing it in Rails if you are familiar and comfortable with both. If you aren't comfortable with both, then that's fine.
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: " @state])))Porting most React code to Solid is pretty easy - 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 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.
I would hope that while -me- reading any such blog post is almost certainly going to be irrelevant, it might pay off enough in recruiting/marketing/pure nerdery to be worth the effort to write it up.
In my current project I'm using Vue with Composition API which gave me the exact same "aha" moment the author of this article had with SolidJS. Vue + Composition API is way more similar to SolidJS in principle than React + Hooks.
I do, however, keep finding myself wondering about jumping to Vue and VueX instead.
Ask me in five years, I guess.
I've been on this quest for a long time, because I like React model. So I had fun with putting observables in my app (kefir and karet from calm-js and my own thing with xstream), I tried custom selectors with redux and all 'like-redux-but-simpler' libraries, I also tried recoil. These solutions can work and worked for my apps, but it felt like I was fighting against React.
Solid was nice. It provided necessary tools to write interactive data visualisations with ease and in performant way. It has quirks but they are manageable - my team also learned and contributed to projects in Solid.
First, the concept of "component functions" that are more like factories. It is not groundbreaking (reagent had this idea long ago) but is quirky. Thankfully, half hour with Solid playground and everybody can see what code is generated and how it works under 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 understand the trade-off but it trips users (me included) that you can't just treat it as regular object. Sadly, only solution for this is lint rule - yuck. But it is much simpler rule than hook rules - just don't destructure props.
In the end, Solid is great tool for "web apps". Think about dashboards or diagram editors. Cheap components, fine grained reactivity, focused updates yield great performance results without jumping through hoops.
May I interest you in Angular? It certainly isn’t cool and I really do hate it. But especially since the AoT compiler has been implemented, performance is quite good. There’s templates, which some folks seem to love. Angular keeps in-memory references to all dynamic elements in a template so they can be updated with high efficiency. It has class components. It has a lifecycle method that is called OnInit. So maybe give it a whirl.
Angular front-end, Nestjs backend has fast become my stack of choice. It greatly minimises context switching by having such similar paradigms across frontend and backend.
[0] - blog series I wrote detailing Angular best practices that I learnt along the way: https://link.medium.com/ncYgWgnK2nb
I think Zone.js is insane.
I know Angular very well. That’s 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.
I generally spend much of my day writing perl. It absolutely works for me, but every time I encounter somebody who wants to -attack- perl I find myself disappointed by how short their list of reasons to hate it is compared to my own.
(one of the most complicated JS codebases I work with on a regular basis is in angular, and the learning curve is a fucking cliff but yeah, once you get to the top, I agree with everything you've said about it)
Why? Because of the ecosystem! Do I need accessible, headless components? Use React-aria from Adobe! Do I need state management? There are many established ones, I just need to follow their best practices. Everything supports React, every hire speaks React, and it works, not like "just works", but "... works" and, disappointing to the engineer inside me, this is not something I can trade in big projects.
It is a huge performance issue.
I tried to do a pokedex in react, you have to use a virtual list, because react/virtual dom is too slow, doing any operation on a plain list with 1k element, like filtering lead to multiples seconds freeze.
This also lead to a lot of issues, like not being able to ctrl+f text being out of screen in a virtual list.
Deleting it 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) and that I had way more node per entry, it led me with way worse performance.
Instead of a plain list I have a little summary card per pokemon (which is why I have more node per entry).
The naive implementation in Vue run flawlessly(sadly no preview):
https://github.com/Kuinox/kuinox_pokedex/
Note that the react implementation do weird thing because I tried to get around the issue without success.
https://codesandbox.io/s/hidden-dawn-odm1m1?file=/src/App.ts...
Building apps on it show consistent subpar performance.
Rendering a page server-side and delivering it to users is about as inefficient a process as you can get unless you have massive resources dedicated to an optimization almost no one needs anymore. The virtual DOM is extremely efficient, it just needs more memory and CPU cycles on the client which are resources readily available. 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.
It cause an issue: now the search in document browser feature will not work properly.
This is acceptable the usecase you are describing(due to the huge dataset), but 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, you can't ctrl+f a project outside the screen, even if it exist, you have to scroll to it.
> Rendering a page server-side [...]
Nobody talked about server side rendering there.
> The virtual DOM is extremely efficient
Did you read the article I linked ?
The virtual DOM is not "extremely efficient" it's only good at removing uneeded DOM modifications. Not doing these uneeded modifications in the first place is faster.
I would note however that my laptop is not entirely recent and I'm using firefox and my big pain point has been React Native Web apps like web twitter. So you're likely still mostly right, and the question inevitably becomes "how much mostly is enough for any given application".
Does some impressive compression tricks that results in it being remarkably snappy.
You may prefer to run Xvnc directly rather than use the wrapper script, depends how you want to set everything up.
I will be honest here that my setup is not properly automated yet because it's inside a jail on a FreeBSD install and the underlying box gets good enough uptime that my current half-assed approach hasn't yet annoyed me into finishing it.
There weren't any interesting gotchas though.
Knowing that your entire UI is running inside a function that gets re-executed with every render, gives a tremendous amount of safety and predictability to your application and makes testing a breeze. But you can't actually rerender the whole world every time because performance, so instead React relies on a JavaScript object to hold a representation of the UI, and then surgically updates only the pieces that need updating. This was React's big thing.
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.
There's no rules of hooks, no dependencies arrays, no stale closures, no wildly different resulting performance depending on where exactly you put your components boundaries, no VDOM at all, no props diffing, when I change the state corresponding to an attribute or property that just gets updated immediately, the way deep DOM nodes structures are created is sooo much more efficient... it's amazing!
Does the <Counter /> component reference the same outer "count"? So is "count" here global or local to the component? In other words, what is the scope of "count"? Does it change based on where it is placed? If I create multiple <Counter /> components, do they all reference the same "count" or is it 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).
In react, everything is a function and all your code runs on every render unless you specifically tell it not to. This really encourages a certain style of writing code and provides a lot of guarantees about safety and scope.
Solid is literally the polar opposite, your code runs once, and only the parts that you 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 one lousy react app telling me that it doesn't) and Solid optimizes for speed and simplicity.
Solid is very well designed though. One of the features I loved is that Ryan specifically built it to work as possible to vanilla html/js so you can copy old stack overflow answers.
export default function ParentComponent() {
const [value, setValue] = createSignal("");
return (
<div>
<ChildComponent value={value()} />
<input type="text" oninput={(e) => setValue(e.currentTarget.value)} />
</div>
);
}
const ChildComponent1 = ({ props }) => <div>{props}</div>;
const ChildComponent2 = (props) => {
const value = props.value || "default";
return <div>{value}</div>;
};
const ChildComponent3 = (props) => {
return <div>{props.value || "default"}</div>;
};
const ChildComponent4 = (props) => {
const value = () => props.value || "default";
return <div>{value()}</div>;
};
const ChildComponent5 = (props) => {
const value = createMemo(() => props.value || "default");
return <div>{value()}</div>;
};
const ChildComponent6 = (props) => {
props = mergeProps({ value: "default" }, props);
return <div>{props.value}</div>;
};
const ChildComponent7 = (props) => {
const { value: valueProp } = props;
const value = createMemo(() => valueProp || "default");
return <div>{value()}</div>;
};
const ChildComponent8 = (props) => {
const valueProp = props.value;
const value = createMemo(() => valueProp || "default");
return <div>{value()}</div>;
};
The answer is 3, 4, 5, 6. My takeaway is this: there are multiple ways of doing it right, but also a handful of gotchas. The only way to be safe is to keep the mental model of these partitions while you develop, test, debug, and code review. As a code reviewer, you can easily accept 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 better.Unfortunately it's the price you pay for portability thus far. You can build your own language around this like Svelte but then composability is limited (need to rely on other mechanisms). You can make the updates coarser grained like React but then you need a different mechanism(like VDOM diffing) to apply updates granularly. I imagine this situation improves in the future but we haven't gotten there yet.
I'd assume something like es6 proxies for primitive values would be needed, but that, nor built-in reactive primitives, are being discussed currently as far as I know.
Personally, I'd love to see reactive `[].map` equivalents (no need to use <For> components), but that's possible today with a reactive wrapper or (god forbid) patching the prototype.
The setInterval will also keep firing causing, wasting CPU and battery.
It's hard to take any examples here seriously without showing proper cleanup that would pass code review.
Also, composing asynchronous behavior with useEffect is also not a good idea. Don't abuse useEffect as an Event Handler (too much). Think about using Redux (+ thunks/saga) or something similar.
Your naming however reminds me of the RxJS and general reactive programming paradigm I've always pined after... some combination of the two would be my UI state management holy grail.
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 drive its adoption.
While it was a pleasure to use, I was always wondering about other frameworks. But where React really locked me in was in its support. `create-react-app` was an incredible achievement, tbh. It made it so easy to start using React and have all of the bells and whistles out of the box without ejecting. And then, once you do eject, all you have to do is modify your Webpack configuration and you can get all of the additional stuff you want. The community also made incredible packages, like Downshift and Emotion, which further made React an attractive tool.
Over the years the React team has kept innovating it. Hooks made 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 because it was like we went back to HTML generation on the server, but then developers realized that you get the best 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 like Next.js and Remix. I know Vue 3/Nuxt.js exist now, and I know Solid.js exists now, but now 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 it's such a freaking improvement from when I did SSR in 2019 that it's hard to see myself using another framework.
This is kind of a bad answer, but at least I can show you why I'm locked into React I haven't tried any other framework (I also genuinely enjoy using React).
There are some things I don't enjoy about React. I don't enjoy how prevalent Redux is when developers think about global state. I also don't think contexts are a good enough solution (having a good reactive model would have definitely helped here). There are other things I don't like about React: I don't like how often it calls functions; it's extremely wasteful in large applications if you're not careful. And the semantics of `useEffect` are really murky for newcomers (and even sometimes for experienced developers).
If there is something like a Remix equivalent for Solid.js I'll give Solid.js a shot. But right now I'm in love with Remix. Maybe I can use Remix with Solid.js? I'll take a look.
function renderGui()
{
label('hello')
if(button('click me'))
{
console.log('I have been clicked')
}
}Another scenario outlined in the article of rendering a row of buttons, each with it's own click handler, that needs to allocate a lambda for each button every render. Alternatively, using map() and filter() also allocates lambdas and temporary arrays.
All this can be replaced with a simple for loop like:
for (item of items) {
if(!item.isClickable)
continue;
if(button(item.name)){
console.log(item.name)
}
}
Compare this to the React-ish pseudocode: items.filter(item=>item.isClickable).map(item=><button onClick={()=>console.log(item.name)} >{item.name}</button>)
Readibility-wise, it's sort of an acquired taste, I'm not saying it looks better than JSX (but it's a hell of a lot readable than React.createElement, so some syntactic sugar might be put on top of it).However that's probably obvious, so: Assuming you're considering greenfield / blue sky thinking here, it's worth noting that v8 has had so much money and engineering hours sunk into it that the react-ish pseudocode probably doesn't make nearly as 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 good enough 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 please don't take this as a remotely expert pronouncement but "it is, in fact, quite difficult to overestimate v8 these days" seems to be a solid heuristic)
Who knows, if V8 manages it to turn it into a for-loop? I don't, but after a quick googling, as of 2018, it certainly didn't: https://github.com/dg92/Performance-Analysis-JS
The problem with JS is that the execution model is so nebulous, that performance advice basically boils down to - trust in Google.
but if you want to render to the DOM —and you want to use the DOM if you want to have decent accessibility, or not have to reimplement all the complex user interactions that the browsers take care of— then i think an immediate mode framework might have a great impedance mismatch with the DOM, as the latter is a retained mode GUI model
I could see custom hooks being more dangerous and difficult, but Higher-Order Components are too.
No other dev environment for building GUIs has react-like components.
What’s so special about the web that we keep creating frustrating frontend frameworks for?
The frameworks are popular because you can build things incredibly quickly once you know the ins and outs of your framework of choice. The component-style design, the endpoint design, so much is just driven by the needs of web-based development and the framework creator’s preferred way of abstracting away some of the challenges.
In particular, HTML has a tree structure, which means that things that are semantically related on the page and update together are often miles away from each other in the tree.
And the page in the browser is part HTML, part CSS, part Javascript. Frameworks try to let the developer work in JS only and generate the rest.
And finally, much of the application's state is often kept in a backend, and access to it a asynchronous.
I think that's why Web development is so distinct from other UIs.
# Counter.svelte
<script> let count= 0
setInterval(() => {
count += 1
}, 1000)
</script><div>The count is: {count}</div>
<script>
import { writable } from "svelte/store";
function autoCounter(interval, initialValue = 0) {
let { subscribe, update } = writable(initialValue);
setInterval(() => update((n) => n + 1), interval);
return { subscribe }
}
let counter = autoCounter(1000);
</script>
<div>The count is: {$counter}</div>Just different priorities. In Solid you can take that code as is in the component and hoist it out to a function above and presto.. store. It's all the same 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 use the convenient syntax. It is also nice to learn something once and use it everywhere.
very hacky syntax embedded into html. Sometimes you had to even use some kind of comment notation because there was no entry point into the html to add data properties or whatever it had.
it was slow.
the observables weren't variables you could use like plain JavaScript variables
it has the same problem as React - state-based algorithms are not very good ways to solve problems (if (showDialog && !open && ranOnce). You have to keep creating more variables to represent more states instead of using normal programming language concepts, and then all of the observables ping around and become complicated.
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.
But Angular was also so convoluted and had so many problems that so many people kept running into random problems all the time and had to ask questions about them on SO. This signals (incorrectly) that Angular is popular, driving more people to believe it's worthwhile to adopt it.
Knockout had neither. It was not sponsored by a corporation. And it was so good that you hardly ever run into random problems.
Ultimately it was eclipsed by React and Typescript because lack of type checking for the html templates means it's hard to scale it will to large projects.
Before you say it's because I'm "doing it wrong", 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 only see in the debugger). This problem in reactivity is a issue in React that even the best devs can struggle with. My solution was simple... use useEffect less. Depend less on reactivity.
The bottom line for me is that I feel like I can accomplish anything in React, but the devil is in the details. There are so many scenarios that I would need to vet with Solid.js, but if it works better at managing a complex app's reactivity, it could be very compelling.
I am extra skeptical of any 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.*
render() {
return <div>The count is: {this.state.count}</div>;
}
This is not Javascript and it will need to be compiled into Javascript before it gets executed.But you can do the same in Javascript:
render() {
return `<div>The count is: ${this.state.count}</div>`;
}
Using regular Javascript makes my life a thousand times easier than having to go through a compiler to make things work in the browser.React.createElement('div', null, `The count is: {this.state.count}`).
With Solid you get the choice, you could use JSX, Hyperscript functions or template literals like in your example. Solid does recommend using JSX because there are some tradeoffs to using template literals without compilation, but it still maintains almost 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 have to use any templating languages, you can take care of rendering yourself using the tools that the framework gives you. Solid at its core is more of a capable state management library similar to MobX but designed to be used as the only reactivity engine unlike MobX which is usually used on top of React.
If the state comes from the user, they
can add script tags into the html
How is that different with React?And how is it a problem? A rendering engine would set the html of some element to the html I think?
This ...
document.body.innerHTML='<script>alert(1)</script>';
...does not execute the script.https://developer.mozilla.org/en-US/docs/Web/API/Element/inn...
But the same issue with reacts way.
This seems to be quite a good way to compute and apply complex state to a component. In my opinion better than useReducer().
But to be honest, for most components useState() and useEffect() are totally enough. And if you do something wrong like in the counter example, you see it right away.
Is it though?
I mean I happily write more code for a single-page Vue component for something like this.
Terseness is not always a virtue.
This is a subjective thing, right? Personally, I hate boilerplate: either it's a distraction because it's boring and superfluous, or worse it's long and it's wrong. Regardless, it adds to the cognitive load when maintaining code.
There are several terse syntaxes I really like. I'm just not convinced it's a virtue in this context.
At this stage, size of community is a really important factor, overriding many other factors.
It's just incredibly important for there to be tools support, questions answered on stack overflow and a community of people developing related software.
At this stage there's only really VueJS, Angular and maybe one or two others with community large enough to justify changing.
And that's doubtful decision. Each live 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.
I love the new ergonomics (hooks, useEffect, redux tools) but I definitely hit the exact issue OP mentions almost immediately.
I don’t feel that the solution react provides is too out there, but agree it could be better. The react ecosystem still makes it worth the one or two “could be betters” for me.
In 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.
The other big benefit is that you can test the reducer without the component. And compared to redux, it still has a smaller footprint. So it doesn't have the dependencies, you don't need to setup a store etc.
[1]: https://www.solidjs.com/guides/faq#is-there-react-compat%2C-or-some-way-to-use-my-react-libraries-in-solid%3F
[2]: https://github.com/solidjs/react-solid-stateI create a library at github.com/thebinarysearchtree/artwork. To be honest, I don't know if it is going to work or not. It is just javascript with no reactivity. When I rewrote a fairly typical large application that you would find at most corporations (not a giant tech company application), every component ended up being about 50% of the code of react, with excellent performance.
The problem I have with it that makes me uneasy is that ultimately you are creating content in JavaScript, which I don't think is ideal. The lack of HTML structure isn't a problem as devtools and so on show that. The problem is things like:
const label = label('Email:');
I want the HTMLLabelElement variable to be called label... but that is the name of the function that creates it. Then there is the setText example on the github page... I just 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: const content = div({
className: 'content',
title: 'whatever',
innerText: 'something'
});
it doesn't look like art, which is the point of the library. It is just hard to create content with JavaScript and not really the tool for the job. If I could solve that, I would be very happy with the library. It kind of needs JSX, but then it is back to having the JSX variable auto-update the state and well.. I guess that is why knockout and so on do it. Maybe I could do just plain HTML without state.So yeah, I don't know. I mean, it does end up being half the code. If you look at the todo example on my github page, and compare it to the one on React's homepage or solid's homepage, it is literally half the amount of code with native hand-written performance. This continues on to real-world components, it is just that.. I am a perfectionist I guess, and I want it to be elegant always.
anyway.. I haven't even finished writing the documentation.
I've been using Lit.js for about a year now and something about it just clicks. I just wish it were more mainstream.
I used Vue.js for my last development, and I see no need to trade Vue.js for something that's both more complex and has less performance.
Hooks allow you to bundle code together by functionality, and consequently allow you to easily extract and share said functionality in a very composable way.
This is my go to for visualizing the difference: https://i.imgur.com/e9K8vfz.gif
You’re using React. The mechanism that enables code reusability is through composing components.
There’s nothing wrong with class components even for the most complex logic. The only downside is the community has moved on and mostly adopted hooks and functional components.
If you think that this:
return (
<Apple>
{({ apple }) => (
<Slicer slice={apple}>
{({ sliced: slicedApple } => (
<DinnerPlane contents={slicedApple} />
)
}
</Slicer>
)}
</Apple>
);
is more desirable than this: const apple = useApple();
const slicedApple = useSlicer(apple);
return <DinnerPlate contents={slicedApple} />;
Then go for it I guess.Although you'd have to somehow ignore the fact that you'd end up with an even bigger mess if you want these intermediate functionality steps to interact with the parent component in a non-trivial way, ..
Needless to say, I have written such render-prop and "renderless" components in the past, and I see very little upside compared to hooks.
function FacebookComment({ commentId }) {
const comment = useGetComment(commentId);
const likes = useGetLikes(comment);
return (
<div>
<span>{comment.text}</span>
<span>{likes.length} likes</span>
</div>
);
}
I don't think deal with more braces right now to bring the alternative into existence unfortunately <DinnerPlate>{...map <Slicer><Apple /><Slicer/> }</DinnerPlate> componentDidMount() {
I get driven away from React. It looks haphazard. Seriously? What about componentDidntMount() {
componentWantedToMountButDidnt() {
...I'm used to clean naming conventions like
void Component::on_mount() {
....
}For an uncommon use example of what could be possible:
(defmethod react.component:mount :after ((self counter)) ...) ; instead of componentDidMount
(defmethod react.component:update :around ((self counter)) ...) ; instead of shouldComponentUpdate
(defmethod react.component:unmount :before ((self counter)) ...) ; instead of componentWillUnmount
; (the react.component namespace qualifier could be whatever else and not necessarily typed out)
However closely you integrate it with the language, having that machinery generally available seems better for naming and for providing new lifecycle functionality, without everyone having to reinvent the wheel and provide it in different incompatible ways. But it's clearly not a big issue.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(), because it breaks when async rendering is enabled), which is called 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 before it (where you can return true/false to tell React whether or not to proceed with the update) and UNSAFE_componentWillUpdate(), called between those two.
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 cloud-native Vue interface.
I tried to put the code up on GitHub but it wouldn’t let me upload a 10gb repository (and that was without our proprietary fork of mysql :)
We are running an enterprise-scale Angular 13 "SPA" that blows the prior platform out of the water.
It just depends on the team and the goal.