293 points · by feross · 5y ago · 331 comments
Svelte is both succinct and powerful. I find this in contrast to React which is often baffling and incoherent. I say this as someone that has used React professionally for 6 years. They've changed their mind at least 3 times on the API and none of it fits together today. Hooks and classes don't mix, lifecycle methods are still out there and just as confusing today as they were years ago. Mixing state and functions. It's just a horrible bag of half-baked bad ideas. And it's not even batteries included.
Svelte has it all built-in. It has the equivalent of CSS modules. It has global reactive state and an incredibly simple state protocol that seems almost stupid if you're coming from Redux. You step out of your daze and realize you don't need all the rituals and boilerplate. The things I've seen built on top of that simple protocol can be incredible. It's not magic. It's just JavaScript.
I dare say that Svelte is a joy. But I hesitate to even leave this comment here. Because I know the architecture astronauts are listening, eager to sink their claws into this simple elegant new thing and fill up their Github profiles with soon-to-be abandonware cruft which they will use to pad out article after Medium article which will all pour down upon Hacker News like a shit typhoon. Prodding us to join their cult of Svelte+RxJS. Or Svelte Sagas. Or their random dogma they toss into a giant bucket labeled "Svelte best practices." And, of course, "Ten ways you are doing Svelte wrong."
I might be a little bit cynical.
From Svelte: {#each cats as { id, name }, i}
JavaScript already has facility for loops and mapping, and relying on that will automatically get you tooling/IDE support. React handles this aspect quite well, and to me that's a point in favor of React.
I do agree with your post - especially on hooks being a step backward.
This is why, for example, Solid.js does control flow through <For /> and <Show /> components instead of map/ternaries even though it uses JSX.
Such as:
import * from "svelte";
// ...omitted for brevity.
{
svelte.each(cats, ({ id, name }) => <p>Hello {name}</p>)
}
// ...omitted
This is easy to parse and transform, while being fully within JS.Which is why we use JS and allow V8/SpiderMonkey/JSC to do it for us :)
But with Svelte 3 I actually agree with their choice now:
1. The extra templating syntax is rather small and concise. And explicit.
- There are very few directives, and they follow the same rules: `{# start block }{: alternative branch}{/end block}`
- external data that comes from Javascript is always `{data}`
- properties of html components that can be bound are always `prop:name|modifiers={data}`
This is in contrast to, say, Vue, where the syntax can never decide where it's going.
And compared to React, this isn't Javascript either if we think about it:
{
svelte.each(cats, ({ id, name }) => <p>Hello {name}</p>)
}
That's a specific extension that compiles to Javascript2. Your work becomes MVC-ish
Your template/html becomes "I have some data, let's display it". And since the template syntax doesn't allow arbitrary logic, you end up collocating transformations of your data with the code that's fetching it. Instead of doing some weird logic inside the template like `data.map.filter.map`
3. But to each their own :)
What really turned me towards Svelte is going through the tutorial and then trying it. It really is good :)
Now Svelte, I haven't been following, but I think the creators are working in what's going to be next and even better framework[1], to your point of things in Svelte not changing as much as in React, maybe it just a matter of time. Here is the video I had in my bookmarks for a while, I still couldn't make the time to watch, so I hope my comment is not too far from reality.
Go watch the original React debut talk and ask yourself if React had/has anything going for it beyond Facebook's backing. I know I, and most developers I know, dropped Backbone/Knockout/whatever instantly to use React because it was so obviously better.
Now that unidirectional flow is the state of the art, the difference between the main frameworks just isn't that big. You gain a few things here, lose a few things there, and write a solution that is similar to what you would have written with the other frameworks.
You skipped a huge step. There was angular before react. Which was horribly bloated and over complicated. People wanted something simpler. React, with it's facebook clout won in the end.
I personally heard that 'objectively better' line incessantly from 2015 onwards, with 'it has the largest community' always being a top highlight. Facebook's backing and the celebrities that developed in the JS community around the time certainly played a part in it.
I was working at Groupon and using Backbone at the time and found nesting components to be a major hassle. We used a framework called Thorax on top of Backbone, which helped but still fell far short of React's convenience.
That's not what I intended to say, of course that's not the only reason people choose React, but I think they are valid reasons to help you decide.
For example let's say two libraries are technically different but equivalent productive and nifty, choosing the one that has a bigger ecosystem is a totally valid choice.
Many people had to sell React to their bosses, and the fact that there was a presentation by Facebook, helped a lot, I don't see how stating the obvious is calling lemmings to anyone.
At the end of the day, it depends on your goals and motivations, I can't talk for everyone, I was actually saying some of the reasons that helped me decide on choosing React.
I would argue that react has some particular merits (for three the whole vdom based architecture, using jsx, and unidirectional data flow), that it was the first (widely known) framework with those merits, and that it has generally been backwards compatible or only required simple changes. I think these do a better job of explaining why react became popular and inertia explains why it is still popular.
> jQuery
Just not possible to compose, which makes full applications difficult. No answers for state management or such either, completely a different scope than frameworks
> Google more clout than FB
In some domains sure, but I’ve never understood how people don’t think FB are masters of UI. There is probably no org with more UI clout than FB, they built their own insanely adopted library after all while Google can barely force their own engineers to use Angular
React is also unquestionably the most JavaScript of the libraries, a component’s markup is such a thin abstraction around an object and maps perfectly to DOM trees and concepts, classes or functions or hooks are all using native JS concepts, explicitly typed typescript and react genuinely eliminates the need for all simple testing plus makes for a streamlined developer experience, and its concepts of lifecycles and composability introduce complexity but in my opinion in a clearly delineated and extremely powerful way
Also, as always I have to note this, the churn argument is completely overblown wrt React, each way of writing code still works or compiles, conceptually the lifecycle and state management never changed just its syntax, and npm has old versions for a reason. I run 2016 code in production today as an internal application for engineers, and I’ve seamlessly updated webpack and module versions while keeping the same code syntax.
Yep, and my interpretation is that, that (the widely known part) happened because it was backed by Instagram first (if I recall correctly) and then Facebook.
And not to invalidate your point but to add another speculation on why React became more popular...
Yes, Angular was backed by Google, but not used in production in massively successful product as Facebook, or Instagram, and I remember also about writing Directives, Services and it wasn't very inviting for third party packages.
When react came out, I remember the selling point was "it's not a framework, it's a library", "it's the V of MVC" and I think that strategy also helped to let the community create all the other pieces, and long term have a richer ecosystem.
I also hear about “react doesn’t have one way of doing thing’s built in”, but it wouldn’t have been as successful if it had. It ate up other frameworks because it was so easy to integrate.
Need more performance in your angular app? Just add an ng-react component. Have an extensive backbone project? You can just gradually swap in react to replace your mustache templates and leave backbone alone. Have a jQuery widget that’s getting hard to maintain? Change to React and the rest of the page renders on the server like it always did.
And of course, you could greenfield with flux, rxJS, or whatever other thing worked for your company. But if they hadn’t been flexible from the start, there wouldn’t have been room to create and test things like reactive programming, redux, mobx , etc
It's very thin syntactic sugar over a function call. It has a very simple 1:1 mapping to the output code, as opposed to "magically reactive `foo = bar`.
> I'm sure not many people would be willing to argue that throwing promises (as react suspense supposedly does) is a holy grail of frontend development, even though it is "just javascript".
I'll give you that hooks and suspense are straying further from normal js because they don't behave like normal functions do and have special rules for being called; hooks are a DSL for encoding incremental computations into js, and suspense is just the react team fawning over algebraic effects/delimited continuations and trying to reproduce them in js.
But then again, all of these can be defined in normal JS code as opposed to a DSL which compiles to who knows what, so all the rules applying to normal JS and its tooling apply to them.
That's not the case with Vue, Angular or Svelte. There's framework specific syntax that you need to learn. Eg: '{#each things as thing}' from Svelte's documentation.
Counter in this example is likely a proxy object that knows when it‘s changed and tells svelte to re-render.
It‘s also not immutable, which can cause very confusing interactions in global state.
I ended up not using it though, as the surrounding ecosystem just isn't there. There are two different material design frameworks out there for Svelte, neither of which I could get to work. I ended up opting for Angular+Angular Material, which worked out of the box.
I very much like the idea of compiling code to make direct DOM mutating managable. A very powerful idea regardless of which syntax you end up going with. I wish their website talked more about this instead of having a React comparison on every page.
IMHO, it's a disservice to yourself to just blindly drink the immutable koolaid without understanding the very real drawbacks it comes with in JS-land. There's a great deal of gray area where explicit mutation is perfectly adequate in ways that overzealous immutability might be counterproductive.
To be fair, after looking how the whole Redux story went, I think the mainstream simply wasn't ready for immutable state.
I'm still a big fan of the developer experience Vue provides and I'm locked into a framework for my work projects so I won't be switching those over any time soon, but I've been meaning to try out Svelte for a personal project some time.
No longer the case. Vue 3 was written to have a "compiler-informed Virtual DOM"; there are a bunch of videos about it on YouTube if you're interested.
However the issue with both svelte and stencil is their lack of ecosystem, even if they have interop with webcomponents, today the market is too small.
How does this scale to anything remotely complex?
I've found that if you have a decent knowledge of React it's hard to make anything slow with it.
Yes, both of the creators now work on the React team (Dan Abramov and Andrew Clark), but it's always been an independent OSS project, and is currently maintained by myself and Tim Dorr.
As far as I know, FB barely even uses Redux at all internally, and that only in isolated particular teams that chose it themselves. My understanding is that they mostly use Relay for the new FB.com, and still have a lot of old-school Flux in there as well.
My commentary is more directed at React and Jest (as I try to steer away from that ecosystem, even though it's ideas aren't all bad):
- As GP indicates, React has had multiple API implementations to solve similar problems, feature bloat, leading to opinionated and differing best practices, mixed in with Junior devs can be a nightmare
- With Jest, I find the entire thing as a very aggressive wrapper and very tied to React itself, features like unit test `snapshots` are developer slack-off bait and have the benefit of further entrenching itself into the repository, arguably an e2e test would validate the same thing
The source I have says that Dan Abramov created Redux while working at Facebook on React[0]. So while Redux has never been under the official governance of FB, it was created by FB employees for a FB project (React) while in parallel working on that project.
[0] https://golden.com/wiki/Dan_Abramov_(software_engineer)-99B8...
This, so much. It has been so frustrating to have to go from es5 classes to es6 classes + stateless functions to stateful hook oriented functions that do nothing but create just a new type of class, but also with es6 classes but with different methods. Seriously, WTF?!
I really like the ideas behind Svelte, but some things just really do not mix well with it. Like leaflet or d3. For some reason, mixing declarative rendering approaches with non-declarative approaches results in completely mind boggling buggy interactions that aren't easily understood. And typescript integration feels tacked on and doesn't play nice with some of the semantic differences between svelte and javascript, which makes me doubt how much you can really say that it is just Javascript. I mean the entire concept of a variable has completely changed to become reactive, and at that point it's not really javascript anymore, it's something that compiles to javascript while looking almost exactly like javascript. I'd love to give it a deeper look, and I probably will soon, but I'm quite skeptical of what might be hiding underneath the covers.
- has a test suite
- integration with some backend framework (including secure auth)
- complex global state management requirements
- routing
I don't understand this worry, but I guess that happens when you try to do everything with hooks, the way I settled in my approach is to use React components just for the view without hooks, nor lifecycle logic, just dumb components with ocasional local state (useState)
Then using Controller pattern, within the controller I use 4 types of hooks, 1 navigation (useHistory), 2 read global state (useSelector), 3 dispatch an action (useDispatch), 4 useEffect() to execute on props change or component mount.
That's it, that's where the realm of React and UI ends for me, everything else is in Ducks, Ducks are single file or folder per module that contains Actions, Epics (Obervables) or Sagas (generators), Reducers, initial state of store and Typescript types.
I really like this separation of concerns:
- dumb components: to worry just about the looks and local state.
- controllers: to worry about data in, actions out, life cycle and navigation.
- Ducks: Management of data fetching and global state.
I wrote this from the top of my head, but if anyone is interested I'm thinking about writing a demo repository and document this approach, maybe others have done it already this is not new, but practices that I've been collecting along the way.
Let's break down the terminology:
- hooks
- useEffect
- useHistory
- useSelector
- dispatch
- action
- useDispatch
- ducks
- Actions
- Epics (Observables)
- Sagas (generators)
- Reducers
Most of those terminologies don't come from a general programming paradigm, but are the domain language of specific libraries. And I've seen more, with some places establishing patterns like Compound/Molecule/Atom and such. There's no consistent, underlying principle with them, though. If you're invested in Sagas then you're stuck with a bizarre threading model implemented with generator functions and it's pretty much all-or-nothing. If you're invested in Redux then there's no breaking out of that either, you're always going to be contending with shared global state.
I really hate to think how many collective hours have been wasted on new coders who learn JavaScript as their first language --- especially when starting with React and Redux, as it's often taught --- and end up spending most of their time spinning their wheels on these domain-specific complexities, when they haven't even gotten to "while loops" yet. This may even be harder for beginners than understanding, say, one of the classic CS sorting algorithms. New coders don't realize though that whatever degree this stuff is harder, it's a sign of bad tooling or documentation, not that it's somehow intrinsically a harder problem in math / CS, since if you're new you don't know what to expect
That alone is a concern, because any junior programmer getting an introduction through React is going to get a twisted understanding of the language itself.
As a beginner, you should start with plain JS/TS. When you dealt with the hell of manipulating DOM elements all over the place and untraceable UI updates after hours of debugging, you should move on to some UI library. Only then will you understand and see what problem it solves. Then you should go with React, but not hooks or redux. Use plain old classes. When you felt the pain of distributed mutable state all over place, you will be open to hooks or redux etc. Still, do not add a library for thunks. Only after you realize how much boiler plate code you write to deal with async stuff, you will see a value in the added abstraction.
A beginner should start simple, and really feel the pain. Only then will there be an "a-ha!" moment where you can judge if a library/framework actually helps you and provides value.
The biggest issue in FE world is people proclaiming some given conglomerate of a library/framework soup as the silver bullet to all problems.
Don't feel to bad for them, that's our entire craft. `while(true)` and sorting algorithms are not.
- Dependency Injection/IoC - Containers, Resolvers, Scopes - Microservices (Circuit Breaker anyone?) - DDD + CQRS (i could fill a whole page with terms coined by those) - Mediator Pattern etc.
If you buy into a certain techstack, it will always bring associated patterns that have nothing to do with the original language/idiom.
Once you understand hooks in general, any specific hook should be quite straightforward so they can collapse into one. Hooks are quite novel, but I don't find them to be overly complicated unless you're dealing with an already complex situation.
Dispatch, actions and reducers can be collapsed into one since they rely on each other. I think this paradigm is not too dissimilar to message passing with something like RabbitMQ. Reducers are a common concept.
Ducks and Actions, Epics and Sagas are just a convention. It's not required to use React or Redux.
If you try to learn everything at once, of course you're going to get overwhelmed. But the same is true for almost any area of Software Engineering.
To me the proxy object (or proxy class) is really the best abstraction - much like valtio. Or a compiler like svelte.
There’s no reason for ducks, epics, sagas, etc etc. We have a programming language already, we should use it.
If you ever did VB development in the 90s, you will know how easy it was to get a basic app running with those fancy Drag'n'Drop RAD tools. But there was no networking, everything worked offline. But then came the web and the networks, and now everything has to be a distributed system.
Dispatch is how you emit an event (pub in pub/sub). Action is the event being emitted.
Ducks is a code organization paradigm (colocation, organize by feature instead of layer).
Reducers are what they sound like: a reduce function.
Sagas and observables are how to perform side-effects in your application.
There is nothing new here. You could argue that hooks are the weird ones but they are heavily inspired by algebraic effects.
Not really? Most of these concepts can be linked back directly to earlier from CS theory and/or other languages. For example, Redux taking inspiration from FRP and functional lenses, or (most pertinent for this thread) hooks being a facsimile of algebraic effects in JS. As much as I like these concepts in general, I feel some go too far against the grain of what is idiomatic in the language and incur unnecessary friction/spooky action at a distance because of it. For example, here [1] are some well thought-out critiques of hooks and why people struggle with them from experienced JS framework authors.
I agree. Frontend is tough, but so is development. ;)
You don't even realize how bad the boilerplate is until it's all gone. With svelte and some writable and readable stores, I can build apps in a fraction of the time because every time I want to make a change I don't have to start with an action creator, than integrate that into the reducer, then write a selector, then pull it into my component. Oh I guess I need to write an epic with rxjs to fetch the data.
Svelte has 2 primitives that replace all of this: readable and writable. You can create a writable store and you call `.update` or `.set` like react setState. Want to separate your update logic from your component logic like in redux? Easy, just export functions to update the store instead of calling `.update` in your components.
Then, there's readable. Now, readable can be used like a reselect selector, but it's also far more powerful. You can subscribe to changes from a writable, or even other readable stores. You can create a readable that fetches your data. You can create a readable that subscribes to firestore collection or document. You can make a readable that combines data from multiple sources. It's all clear and composable. And I didn't have to write an action creator with an action constant called `LOADING_PRODUCTS`, and one called `LOADED_PRODUCTS`, and then one called `UPDATED_PRODUCTS`, and for good measure we should also create an action "PRODUCTS_REQUEST_FAILED" that we'll emit from the epic.
This sounds very similar to the experience of using MobX. I evangelize it as an alternative to Redux every chance I get; it's incredible how practical and pleasant it is to work with.
I also evangelize it whenever I can -- I don't want MobX to be forever doomed to its status as a cult hit!
And I don't have them, instead this is how you create a type safes actions with typesafe-actions package.
export const signIn = {
request: createAction("auth/signin/request")(),
success: createAction("auth/signin/success")<{ user: User }>(),
error: createAction("auth/signin/error")<Error>(),
};
getType is a function from typesafe-actions as well.Not trying to sell you on Redux, just to address your point about the constants.
About having to write many Epics, well, end of the day, all the Epics have this shape.
export const signInEpic = (action$: Observable<Action>) =>
action$.pipe(
filter(isActionOf(signIn.request)),
switchMap(() =>
from(signInLogic()).pipe(
map((user: User) => {
return signIn.success({ user });
}),
catchError((error) => of(signIn.error(error)))
)
)
);
isActionOf is another typesafe-actions function...I'm not claiming it's superior approach or faster, it's an approach that worked for me for medium/large apps, to collaborate with other developers.
I'm pretty sure you are right about the Svelte cool things you saying I wish I had more time to look into it.
I 100% agree with this, I also started out working with Redux in the fairly early days of React and while I do feel that I did learn a lot from it and have used Redux-inspired patterns for certain parts of applications since then, the productivity gains I got from switching to MobX for state management can't be overstated.
Sure, you could argue it's less "clean" or whatever, but honestly 99% of the time it just works, and I'm happy to have the 1% of time where you're debugging where you forgot to add "observable" or whatever in exchange for the 99% productivity boost.
Svelte does look really interesting and follows a similar kind of model to how I work with React and MobX, and does away with some boilerplate/gotchas.
My main concern using it would be around maturity of libraries... while it does seem pretty batteries-included, I have got used to being able to just pull in a library for x, y or z in React and I'd be worried if I started a big Svelte project, I might find myself kicking myself down the line e.g. if I need some component (data table or whatever) that has a mature option available in React. Perhaps people who've worked with Svelte professionally can comment on whether this is a valid concern?
If you get a chance, I strongly recommend reading through the newly rewritten official tutorials in the Redux docs, which have been specifically designed to show both how Redux works and show our recommended practices:
- "Redux Essentials" tutorial [0]: teaches "how to use Redux, the right way", by building a real-world app using Redux Toolkit
- "Redux Fundamentals" tutorial [1]: teaches "how Redux works, from the bottom up", by showing how to write Redux code by hand and why standard usage patterns exist, and how Redux Toolkit simplifies those patterns
The older patterns shown in almost all other tutorials on the internet are still valid, but not how we recommend writing Redux code today.
You should also read through the Redux "Style Guide" docs page [2], which explains our recommended patterns and best practices. Following those will result in better and more maintainable Redux apps.
Finally, we've got an upcoming "RTK Query" API that we're finalizing and adding to Redux Toolkit (inspired by tools like React Query and Apollo) , which should drastically simplify the data fetching story for Redux apps.
[0] https://redux.js.org/tutorials/essentials/part-1-overview-co...
[1] https://redux.js.org/tutorials/fundamentals/part-1-overview
Oh, look, slices, and thunks, and asyncThunks, and extraReducers, and adapters, and fifteen files to tie all this together for every small piece of api or data that you want to send around.
Most of it just comes from the fact that Javascript doesn't have a good built-in way of doing these cycles fo data/store updates. And still, I don't know where the sweet spot of Redux it: it's an overkill for small apps, it's unmanageable in big apps.
However, I will concede that the new hooks like `useDispatch` are nice
I agree that React folks (me included) tend to reach out to Redux much too soon, though.
As an fyi for anyone not aware, there are eslint/tslint plugins for this to help avoid it.
Not that the answer to a complaint of a complex toolchain is more tools in the chain, but it's a wonderful development experience once you develop a collection of tools you really like.
The UI components all have an else render if for some reason they're missing something / it avoids a crash (along with other easy to see / figure out protections)
Of course, what you see is just a tip of the iceberg, having implemented a nice admin and moderator dashboard, keyboard shortcuts, animations, 12 different color themes (in light and dark mode), and more. Svelte just made it all so easy to do. Having done a good bit of React and Angular professionally, and tinkered with Vue, I can safely say (for now) that all I want to do is Svelte. The rest just seem so heavy handed in comparison.
Self promotion: I also run a YouTube channel where I'm slowly building out a Svelte app with Rails API backend. If you're interested in Svelte, please check it out: https://www.youtube.com/user/iamdavidwparker
The one issue I had with Svelte was Sapper - I didn't get on with it (it wasn't a good fit for either of my projects). SvelteKit was released in beta a couple of days ago - I've no idea how much that changes things. I'm hoping I don't have to relearn a whole bunch of stuff to use the new shiny.
[1] - https://rikverse2020.rikweb.org.uk/ (Warning: Poetry!) [2] - https://scrawl-v8.rikweb.org.uk/ - I was quite proud about getting my canvas library to play nicely with Svelte
I plan on migrating to SvelteKit once it's stable, and may start migrating some of my smaller sites over in the meantime.
Also, no need to warn about poetry- more people should write from their heart IMO.
Quick question: which color scheme are you using in VSCode? It looks a lot like jellybeans for vim, which I love.
I think I'm just using the default dark color theme. (dark+)
It's easy to use but it adds 55kB gzip to your project.
https://bundlephobia.com/result?p=@firebase/auth@0.16.4
A couple of comments on the Svelte code.
1) It doesn't makes much sense to use onMount() with listenForAuthChanges(). Just modify the currentUser writable whenever onAuthStateChanged() has an update. Now simply import and use $currentUser in your components.
2) You don't need to use currentUser.subscribe() from your .svelte files as you can use the reactive $: notation for this. You can, if it makes more sense to you, but I wouldn't say it's idiomatic.
For Firebase, will ES modules help with code splitting? The new Svelte kit framework is built by Vite (runs on ES build underneath).
I also trigger init code from my entry point (eg: main.js).
My only complaint is that the Typescript support isn't quite perfect yet, but it's already very functional.
Compilation actually has nothing to do with it. Svelte is fast because it doesn't do all the Virtual DOM stuff, and the DOM diffing. You could very well build Svelte as a library without the compiler, and it would be just as fast.
But the compiler helps a bit with the ergonomics - it's cleaner to do count+=1, rather than setState({count:count+1}).
Last I checked, svelte compiled different code paths for every single component.
This means that most DOM manipulations in real-world applications (not micro benchmarks using the same components repeatedly) won’t ever optimize in Svelte. Meanwhile, the vdom code runs constantly and is hand-tuned to help ensure deopts don’t happen. Likewise, potential optimizations to reuse old nodes and other “garbage” are much easier to implement with a unified DOM implementation. Finally, once you implement the vdom once, you don’t do it again. With Svelte, your code is recreated for every component. This may give smaller component in the short term, but there’s an inflection point (and it’s in the small-medium range) where svelte starts shipping more code for the same work.
I stumbled upon this article a couple of days ago when it was featured on the last issue of Javascript Weekly (19.3.21) and thoroughly enjoyed reading it. The points made in this piece are soundly argued while never hiding the fact that they're ultimately based on one individuals perspective.
Couple of days later and in line with my usual HN-reading MO (and not remembering the title of said article, it is quite generic) I'm looking at the headline of this post and my mind immediately goes «Yeah, I definitely want to read those comments, if only for shits and giggles». And boy was I not disappointed:
It starts off with «I love X because I hate Y», continues with Y implicitly being understood as a function of «Y + 3rd party Z» (and what's not to hate about bloody Z as if that's not a self-inflicted liability) and ends with library authors digressing into low-level technicalities, which, ironically, both X and Y are trying to simplify in the first place, so that ordinary product-shipping folks like the author of the original article and myself can focus on the task at hand: Getting shit done.
It really feels like everyone on here was just desperately waiting for a hook to talk about either their personal preference or their specific set of problem domains instead of adding value to an admittedly mundane but very concise piece of writing.
It probably speaks volumes about my naivety that, after all these years of digesting HN on a daily basis, I still somehow assume that both the subject matter and the tone of a given piece might actually correlate with the reactions to it. Then again, as I said, I came here for shits and giggles, so, if I'm perfectly honest, I kind of knew all along.
Can anyone recommend good, easy-to-integrate alternatives?
It has a long list of supported OAuth2 providers [1].
It worked for me out out the box (DO docker image), and seems to be progressing well. They have some beta Svelte libraries, and it was simple enough to integrate for my uses.
No affiliation, just happy to have found it.
0: appwrite.io 1: https://appwrite.io/docs/client/account?sdk=web#accountCreat...
They have recently been bought out by Okta... Which by some accounts might not be a good move.
... :-|
Authentication/Authorisation (AuthZ) is hard, brother. Implementing what you think looks like AuthZ is easy, but making sure you've got all possible avenues covered is hard.
Getting AuthZ correct and having everything covered is hard.
Security is hard.
Source: see the entire field of security and all the companies, products and services that have been invented to try and solve this problem.
We actually started with Firebase Auth (branded as Google Identity) and moved to Auth0 later for some small differences.
Also though, Auth0 was just acquired by Okta, if that matters to you.
Happy to answer any questions.
Vue doesn't come close to that, but it does look like Svelte is at least a bit better: https://svelte.dev/blog/svelte-and-typescript
I'd still be wary that there are big caveats though. React was designed for Typescript. Javascript projects that bolt it on later tend to have issues.
this isn't true but JSX was made to be "just js" (obviously isn't true either) which contributes to it.
Thanks for calling me mad :)
> thanks to JSX/TSX, and basically all tools support JSX these days
I haven't used TS and Vue together, but Vue 3 seems to have been written with TS, as well as having supported JSX for quite a while. What are the limitations?
Ok, Angularjs worked different under-the-hood than Svelte. It was a dirty checking loop instead of compiler-generated change indicators, which didn't scale as well. But other than this scaling issue, the ergonomics were very similar.
But in the meanwhile the React folks started this whole idea that this mutable state was a bad idea and people seemed to blindly believe the React way was going to be the silver bullet. The widely acclaimed Dan Abramov launched Redux, one of the most cumbersome, boiler-plate-heavy state management systems I've ever had the displeasure of using. And with react hooks there are more performance pitfalls than there ever were with Angularjs. So now everyone seems to realize that they lost quite some convenience with React. React had a good run, but it's time to move on.
Svelte instead opts for compile-time magicks to handle state.
Angular uses decorators to manage state. This has turned out to be an unwise descision because javascript decorators have changed in spec since then.
export class AppComponent { }
export const appComponent = Component(AppComponent, {
template: '<h1>Hello World!>/h1>
// other compile-time instructions
});
How you want to approach runtime state has nothing to do with decorators.And like I said, react promised immutable state would solve a lot of problems, but it turns out you lose a lot of convenience as a developer while not gaining that much.
Which comes down to your point: cognitive exhaustion. The promise of hooks and functional components was that it would make things 'easier to reason about' (among other things). But we all know now that this is just not the case in practice.
I no longer use React in my projects and only use Svelte and it feels great. I'm very happy with it.
1. Community support.
Svelte I think is the "more technically correct" approach, but React 16+ is good enough, concise enough, and it has thousands of community packages already. Svelte still needs way more buy-in for it to be a serious option at our company. We actually implemented a small part of our app in Svelte, but moved away from it because Svelte is still sort of a tinkerer's tool[0]. I really hope it gets more adoption, though. Until then, we're going to be using React 16+.[0] https://trends.google.com/trends/explore?date=all&geo=US&q=s...
Are there actually any tangible benefits to using it over other frameworks, or is this all just a heap of people getting excited because it's "new and shiny" (compared to React, Angular etc)?
- Smaller code size. No loading of general runtime library, and I've heard people argue that each component(or page) has its own runtime (I may be wrong in the details)
- Many common tools are built-in, like stores and animations, and since there's no general runtime, if you don't use a particular tool, it doesn't get included
- For beginners, the tutorial is a blessing, they can pick up the framework while learning Js on-the-fly (I'm doing this with my nephew)
Once you have the runtime, it’s a fixed size. In Svelte though, every new component must carry not just the description of changes, but also reinvent the wheel by reimplementing each time. How many components do you need to reach 4K or even 40k? Even a small app can easily reach the size inflection point.
Also note that inlining code works differently in a JIT. Your code must run hundreds of times to be optimized. In a vdom, that is done almost instantly for all the most critical render code paths. In contrast, infrequently used svelte components are never going to optimize. This has the effect of making svelte look very fast in micro benchmarks which run the same few components repeatedly, but doesn’t reflect your performance when the user opens up something different and winds up back in interpreted mode.
Preact is a nice middle if you’re concerned about garbage. In addition to being tiny, it diffs against the DOM directly instead of using a vdom.
Sure, there's more devs who currently know react.
But "easier to learn react" is crazy. The svelte tutorial is short and awesome.
In the React hook worker code you do not really need to use the `ref` and you can do something like:
```
function useWorker(currentUser, setCurrentPom) { const [worker] = useState(() => new Worker(workerURL))
useEffect(() => {
const onMessage = (event) => {
if (event.data.name === 'tick') {
setCurrentPom((currentPom) => ({
...currentPom,
secondsRemaining: event.data.counter,
}))
} else if (event.data.name === 'start') {
// More branches removed here to save space...
}
}
worker.addEventListener('message', onMessage)
return () => {
worker.removeEventListener('message', onMessage)
}
}, [currentUser, setCurrentPom])
return worker
}```
The reason it works is that `useState` allows you to lazy load something.
You mention two points which make svelte easier, but I would challenge you on those:
> We don't have to keep the worker in useRef, and can just assign it to a variable.
As per my thoughts above you do not need useRef, in fact you just separated the whole worker logic into a separate function which gives us separation of concern and better readability.
> We can pull the event listener code out into a function more easily, as that function won't then become a dependency to a useEffect - at which point we will have to wrap it in useCallback.
I am not sure I fully understand this. But if you are talking about wrapping the event listener code into a function, you can do that and you do not need to wrap it in a callback. Though, I am not sure what we gain out of abstracting the event handling part.
JSX is not a templating language, it’s just syntactic sugar for plain JavaScript. I never have to wonder what new features have been added to JSX, I never have to struggle with extensions to JSX that some 3rd-party library depends upon. Template-based frameworks are akin to Lisp reader macros, and this is especially true for Svelte in that it is a compiler. But reader macros will kill a language’s ecosystem quickly, in that they break composability. JSX was a clear winner over Angular’s directives for exactly this reason.
Svelte has some cool ideas, but regressing back to another Handlebars or Mustache isn’t one of them.
Svelte seems to be the pinnacle of the "bundling era" of frontend frameworks.
What do you think comes next?
XYZ-to-WASM?
Back the roots with (non-)bundlers like Skypack?
Anyone heard of next-gen experiments in that directions?
For the HTML-over-wire part we are experimenting with a protobufs-based protocol so the backend runtime can support as many languages as possible. The most challenging part is that client-server UIs have fundamentally different assumptions about state, concurrency, and session handling compared to traditional desktop/mobile GUIs that operate on callbacks. Most of the design patterns used for your typical WinForms/Cocoa UI fail horribly in web scenarios (unless the entire app is running client side in WebAssembly) because state must be held in a DB, global variables are completely not allowed and multiple users may simultaneously access a service so any form of long-running loops or blocking code is very problematic. Serverless could help here but you will need long-running serverless containers. The current pricing models of AWS Fargate and Google Cloud Run are not compatible with this.
This is additionally complicated by the fact that many languages have async/concurrency "bolted-on". It is hard to integrate a WebSockets server into the language if there is already another event loop to deal with. This is especially problematic for feature-fragmented languages like Python where async is a relatively new concept. (See https://journal.stuffwithstuff.com/2015/02/01/what-color-is-...) Go is basically the gold standard here. Overall, we are still working on how to build the language-agnsotic backend SDKs without too much duplicate code. If you see similar systems like Streamlit and Plotly Dash, they avoid the problem entirely by making proxying the default way of embedding in third party applications. The integration is not as tight as traditional UI frameworks but avoids many of the problems with state management.
For deployment, the Blazor/LiveView/HTML-over-wire format would also require CDNs that are as close to the end user as possible for lowest UI latency. Think Zeit/Vercel or Fly.io.
There's a mailing list link below where you can be notified for when we launch:
There is yew (https://github.com/yewstack/yew) which is a React inspired Rust framework that compiles to WASM.
Think about it. You can write anything in the script part. Lets say you have a Go UI framework. Write Go code inside script tag and use the template to produce UI elements for TUI apps, for desktop apps without even working hard to manage state, manage UI element paradigms. The simple reactive style of programming can be used. Of course a different compiler can be used. But the possibilities are open. With React and stuff that's kind of difficult. You will eventually end up writing original Go code.
And currently you can compile Svelte components into React/Preact etc. Its not production quality. But its possible. (Svelte2TSX makes it possible)
See https://routify.dev/ and https://routify.dev/guide/installation/install-to-existing-p...
I built an SPA with an Express backend and my biggest complaint was the lack of an official front end router. The community based router libraries had lots of issues and quirks and I didn’t want to lock into using Sapper at the time. Svelte itself was rock solid though and I look forward to trying Sveltekit (think Next.js for Svelte) in the future.
Anyway, here comes the shameless self promotion:
One of things Author didn't directly point out is about JSX. I mean you can build JSX of a component incrementally in your component code. But that's something I am missing in Svelte.
Anyway Stencil is very similar to svelte and support TSX
0: https://testing-library.com/docs/svelte-testing-library/intr...
For end-to-end tests with a real browser, Cypress is a good option.
Full documentation on Github:
The experience was actually really nice. Obviously I don't know how it compares to other options out there, but it was a pretty enjoyable experience overall. I felt like I was able to do exactly what I wanted and wasn't missing anything.
onMount(() => { return listenForAuthChanges() })
and
onMount(() => listenForAuthChanges())
?
For that matter, you could also write:
onMount(listenForAuthChanges)
which is technically simpler -- you're not constructing a new anonymous function. But if you wanted to extend the code (to say, add a console.log), you'd need to do the top version, which already has the braces.
It's up to your judgment of what's clearer and likely to be more maintainable.
function log(expr) {
console.log(expr);
return expr;
}
onMount(() => log(listenForAuthChanges()))There's also some unexpected trouble due to potential extra parameters. Consider the output of
['1', '2', '3'].map(parseInt)
gives: [1, NaN, NaN]
So yea, fn(() => cb()) is the same as fn(() => {return cb()}) – just syntactic sugar when the anonymous function has just one statement. but fn(cb) is semantically different.>onMount(listenForAuthChanges)
>which is technically simpler -- you're not constructing a new anonymous function.
Not just technically simpler, it is a perf improvement over initializing an anonymous function every time onMount is called (which you have already mentioned, I just wanted to emphasize). A minor performance improvement at that, but still, small things add up. I agree with the entirety of your post, however, well-written.