The arguments against JSX and React requiring many small components are very surface level and sound like "we couldn't figure out how to make it work for us so it must be impossible".
1. This was mentioned already, but, yes, you can use ternaries and boolean logic for simple conditionals (loggedIn && <a>Logout</a> || <a>Login</a>)
2. When you need more markup, put them in an if-else statement in the same render function.
render()
if (loggedIn) {
var login = <a>Logout</a>
else
var login = <form onSubmit={ ... } />
return <div>
{ login }
</div>
3. With SFC it's trivial to split these out into new components. You can even use bound methods to reuse the component state and props.
There's a continuum of ways you can structure your code, it just takes some experimentation to find what works for you.
After working with Angular templates for a long time and then switching to JSX, I'm never going back to having my markup in a string blob with magical attributes that make it do stuff.
It's not a dumb question at all. It's relatively new, and I would implore the originator of that comment to take a different tone. It requires a newer browser or some sort of transpilation step. (You're probably already using one if you're using React)
Most of the React community has forged forward with ES6/ES2015, so learning that is definitely a part of the process.
Telling someone, "or maybe you should learn JavaScript" is kind a really jerky way of saying, "you don't know what you're doing". I do think it was a terrible way to share knowledge. Yet it was an excellent way to say, "I know more than you".
I agree it is rather combative, however it's also true. To claim that X pattern is a reason to not use a library when said pattern is actually an anti-pattern you've used because of lack of understanding is going to garner these kinds of reactions.
> And finally, what stops you from creating a custom component that works like this?
I wondered what the issue was myself, so I actually implemented that pattern in a codepen, then looked at the compiled form of the JSX to Javascript.
The essential issue is that the value of a prop is always evaluated at runtime, regardless of if the prop is actually used. In the case of props.children this means that <Then> and <Else> are both evaluated, and thus rendered, and only one of them is actually used.
Thus you can't have conditionally rendering children, unless you've written them to be okay with failing at a render, with a blanket state---which is what most people are trying to avoid writing into their components, and simply want to conditionally render in a higher level component.
Disclosure: self-promotion. It's really frustrating that I see this React-is-crap-because-no-conditionals come up again and again but if you want them all it takes is an npm install and a line of babel config :(.
since then and else are going to be used inside an if component, you can use context to read condition, then not render at all if you don't need to (return null).
I think your comment just proves the point of the original post. Your examples are still not good enough for me in terms of syntax and real work with html guys (specifically, <If><Else> has some quirks). I've gone through these things, and the pain&negativity about Angular 1 which translates to negativity to all template engines was also mentioned in the post.
Our Perl5 CGI.pm codebase used to look like that (html + logic). Fortunately we switched it over to Mojolicious and it became manageable. Not going back there thank you.
> and sound like "we couldn't figure out how to make it work for us so it must be impossible".
It sounded more just like "we couldn't figure out how to make it work for us", which is a perfectly plausible position.
The author just stated that React didn't work for them, not that it's "impossible to use React" as you are implying.
From the article:
> I guess this level of strictness and purity is something that may be useful when you have 1000 devs in your company [...] But most of companies have far smaller dev teams and other goals than Facebook.
Fair enough, but if they're going to write about their opinions and argue that "JSX sucks", they should at least be intimately familiar with it. Choosing lack of conditionals as the issue to focus on instead of any other problems templating in React has tells me that they're not.
After working with Angular templates for a long time and then switching to JSX, I'm never going back to having my markup in a string blob with magical attributes that make it do stuff.
why would you do this in Angular? i thought the whole point was to use html templates in separate .html files. as for "magical" attributes, angular2 moved away from that and is using mostly native html attributes. i.e. [disabled]="x" [hidden]="x" (click)="myfunc()". Can't imagine it being more intuitive than this.
JSX actually makes it more intuitive than that by having 0 reason for even needing to know when to use square brackets vs parenthses. It's simply curly braces and vanilla JS
this is a different statement than the sentence i responded to. square or round just indicates the direction of the binding. everything in angular is also vanilla js.
I think what he means is that control statements don't exist in JSX. You have to write Javascript to do if-statements, looping, etc.
In React, there is no 'direction' of binding---its all one way, just like in vanilla Javascript, and in fact no binding on anything except low level elements' like divs. Components only receive props, which do not do anything at all until you write code that reads them and runs operations based on their values.
Thus components are simply function calls (it's what they compile to anyways), and JSX is just a syntax to write functional code.
It's not just you...this has been a pretty big toss-up with MVC style frameworks and view libs. Does business logic belong in the template? Or does it belong in some sort of view controller? Mustache.js insists that all decisions should be made before data is sent to the template. Most other libs allow the template to make decisions. I don't think there's a definitive answer. I kinda lean on making easy decisions in Handlebars templates... or, since our new app is in React, JSX.
When I first started using React, I was very concerned about the lack of template support for conditionals.
In practice, I've find that I now segregate heavy logic into it's own function, which ends up making my components very readable. The lack of first class support for conditionals as a part of JSX has forced me to encapsulate code better.
I would say the only trade-off I've noticed is I end up losing a little bit of DRY-ness here and there with some components having near identical functions. I think it's an acceptable trade off as long as functions are small.
What exactly is elegant and simple about that? I feel like this kind of syntax would break down on more complex examples, is that not the case? What would it look like with multiple conditions (say something like A && B || C)?
What on earth does not break given more complex examples? That's a bit of a non-argument. The mustache example is a direct translation of the jsx example, so keep things in context.
As for your multiple conditions question, what exactly is the point of that? All l see is code, no data, no markup. Completely irrelevant.
No need to get so defensive. I'm just curious how it holds up in more complex examples. I know how JSX does because you just use the same concepts you already know from JS. But Mustache seems to have its own custom syntax, so how well can it express more complex cases?
After all, we're not just displaying "Hello" or "Please log in" all day.
I simply responded in kind. Notice the difference in tone from your first response, and this one.
To answer you question, you use JS! Or PHP! Or any of the other 2 dozen languages Mustache supports. Mustache is all about logic-less templates, which by definition assumes the logic is being written elsewhere. Edited my example to make that clearer.
EDIT:
const tpl = "{{#loggedIn}}Hello{{userName}}{/loggedIn}}{{^loggedIn}}Please log in{{/loggedIn}}";
Mustache.render( tpl, state );
Hmm, I see what you mean about pushing logic to the code calling Mustache, but I still wouldn't call it elegant with all the curly braces and explicit closing tags needed. JSX isn't elegant either in that regard which is why I work with React through ClojureScript.
Explicit closing tags are only needed when dealing with more complex examples, like basic conditional or loops (arrays). Rather than try to teach you on a hackernews forum, you can learn all you need to know about the syntax in 5 minutes here: https://mustache.github.io/mustache.5.html
Yes mustache, JSX and all the other templating syntax aren't pretty, but my point was that Mustache is the best I've come across so far. elegance and simplicity are in the eyes of the beholder though, so to each their own.
Wow. Do people consider this kind of coding acceptable now? We spent decades trying to separate templates, business logic, and inlined JS, and you managed to cram all three into a short snippet.
Yes and this is a tired argument by now. The talk by Pete Hunt aptly titled "React: Rethinking best practices"[0] given in 2013 points out how separating templates and logic is merely a separation of technologies, not concerns.
Whether to show a logout link or a login form is presentation logic, not business logic.
I've spent decades telling people that trying to keep logic out of templates is a waste of time. A useful templating language has variables, conditionals, and even functions. There's no reason not to use a real programming language.
There's no good automated way to enforce MVC. How is an automated tool going to know whether "show this number to two decimal places" is a model thing (inherent precision of the data) or a view thing (presentation choice)?
It's actually no different to any other templating solution. Take a look at this[1] Mustache.js example and note the logic! At least JSX is honest about what it is.
Agree. Looks like those who haven't suffered from it, can't live without this suffer. They just need to have this experience to be able to understand downsides.
4. This won't work if one of the branches errors, because they are both evaluated. You can, however, pass a callback. But a simple ternary operator does look better.
After making some simple <If> <Loop object="">, etc custom components.... I've wondered why they don't exist in react by default, or arent the common pattern.
They are very readable... maybe people just dont like the "logic" in a tag... i guess... whatever, made for some really readable code...
I would rather 'regular' JS functions like .map() rather than React-specific functions like <If> and <Loop> (not to mention the namespace clash with existing JS keywords)
It is basically equivalent to `LoginForm = this.LoginForm`. It is called destructuring and is one of the nice conveniences of es6 javascript. Importantly you can also do this:
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
It destructures this, to get the LoginForm property, it could be written <this.LoginForm> because even if it starts with a lower case character that are transformed as string when there is a dot it is transformed as object :
<component /> compiles to React.createElement('component') (html tag)
<Component /> compiles to React.createElement(Component)
<obj.component /> compiles to React.createElement(obj.component)
One of the most impressive thing about Vue.js was the ability of the framework to enter a field saturated with dozens of options, that was becoming dominated by a well-resourced oligopoly (Angular, React), and still win over developers jaded from Javascript-fatigue.
The give-a-shit factor from Evan (the creator) is extremely high and was key to its success.
Inspiration for anyone building a product in an established market: there's almost always room for better.
I think that, similar to how everyone realized that jQuery wasn't the right tool for certain problems, people are coming to the conclusion that Angular and React+[Flux/Redux/MobX/etc.] isn't always the right tool for certain problems as well. And I think that Vue.js fills the needs for those problems very well.
The truth is, the majority of the work I've done in React for my job on the web would have been much better off written in Vue. React gives plenty of rope to hang yourself with if code quality isn't kept, especially when working with developers who've done nothing but jQuery for the past 10 years.
Vue.js (which, TBH, I haven't used yet - I'm still on the React hype train) looks great when you're working on a project that is complex enough to warrant looking for something more than jQuery, but not big enough to warrant the abstractions presented by React.
I've also found that the paradigm shift from jQuery apps to React is difficult for a lot of people at first, and Vue.js looks like a nice middle ground of "still looks like plain javascript-in-the-browser" while also nurturing some of the same ideas: components, event-driven model, one way data flow.
It also requires no transpilation and has a small footprint.
All of these are IMO a great plus when working in a team environment on sites that require lots of interactivity but don't quite fit into the "SPA" bucket.
When I first started dabbling in web programming a few years ago, I quickly learned about jQuery from SO while looking up common patterns to create the behaviors I wanted in the browser. But even accounting for my unfamiliarity with the browser paradigm, jQuery always rubbed me the wrong way because of how loosely structured it allowed you to be and the amount of leaky scope it encouraged.
I finally decided earlier this year it was probably worth my time learning a framework just to get some structure in my code, so I asked a webdev friend if he had any recommendations for a JS framework I should try; he pointed me towards Vue. I had never heard of it and was skeptical, but I started working through the quickstart guide (Vue docs are great, another +1 to Evan!) and I was hooked before I finished the third example. It was night and day from jQuery, but easy to learn. My experience so far is that Vue (in contrast to jQuery) is astoundingly flexible for how terse it is. My code was probably bad, but rewriting a jQuery page in Vue usually halved my linecount.
>no transpilation
This is huge to people who just want enough JS to get their proposed feature working and don't want their whole site to be JS, and to beginners. True, at this point I have started getting comfortable with the npm/webpack/babel/es6 stack and I enjoy the things it makes convenient - but at the beginning it's a pretty nontrivial learning curve and delayed benefit for a dev team that have probably been doing most things on the server with python or php.
>Vue.js looks like a nice middle ground... while also nurturing some of [React's] ideas
YES. My first three tries in Vue were basically little calculators that hit some APIs and got some user input and displayed data. I had no idea what "components" were and my calculators were quick to write and worked great. I figured that if I ever needed to use components, there was time enough to learn about them later.
A month later, I decided to dig in and grok React. After a couple of good tutorials, I finally get components and why they can be great. I've never used Vue's component system, but now I have faith that they are as much a pleasure to use as the rest of it.
The great thing about Vue is that it's modular. It can be as simple or as powerful as you need. If you just want to define some behavior and have an object with standardized access to hold the state of your page, you can do that. If you want to use portable components to reduce duplication of effort, you can do that. If you want to enforce Flux design, vuex[0] is there for you. If you want to write a full SPA and need a router, vue-router[1] will do it. If you want to use JSX, there's a Babel plugin[2] for that. None of these are around to complicate your understanding of things when you're learning, but they are easy to plug in when you need them. This is in pretty strong contrast to my experience with React, where you get hit with a lot all at once. Admittedly, I jumped quickly into using Redux and websockets because I was using that one great tutorial that everyone links[3] - so maybe React by itself isn't too overwhelming. I won't hold my breath though.
Once components click, everything becomes a component.
That's not a two-bit attempt at Javascript zen, what I mean is that components are basically reusable building blocks of functionality. Mastering them provides an excellent way to reason about your app's structure.
Vue is a frontend framework.
jQuery is a library, with a very specific goal (DOM access)
What happened when you were using jQuery, is you created your own homegrown "framework" on top of it. Thats what you should be comparing Vue with, not jQuery.
> One of the most impressive thing about Vue.js was the ability of the framework to enter a field saturated with dozens of options, that was becoming dominated by a well-resourced oligopoly (Angular, React), and still win over developers jaded from Javascript-fatigue.
When it comes to simple solutions that do no require a build step, the field is not that crowded. A built step should be optional, not necessary to use a front-end library. With Angular you start with the CLI, with React you need to compile JSX files, ...
Angular 1 didn't succeed because it needed a build step or a third party language, it succeeded because it provided a smooth upgrade path from jQuery based apps. The Angular team forgot what made Angular popular with their "enterprise framework".
Is that true? I mentioned somewhere else that being able to use vue.js without a compile step was a breath of fresh air, but I was informed that you can also use React as a drop in library without any kind of compile/transpile/task runner. I assumed the person knew what they were talking about, but I never to research it. So now I wonder what is true. Can react be used as a drop in library like vue.js?
So long as you don't use JSX you certainly never need to transpire. I believe there is also a shim to do client side jsx parsing but is not encouraged for use with prod code
It certainly can, but the current mindshare is certainly against that (for various reasons). JSX can be used with just dropping in a second library, but performance is impacted (it has to do the compilation on the fly). If you want to use the ES2015+ features of React, you'll need a build step in between due to lack of browser support.
The reason for its success is good documentation and simplicity. Anything like this aims to empower users, and get the fuck out of the way and let them do their work has a space no matter how crowded the market.
Angular and React want you to do things their way and therefore get in the way, and then make you do a bunch of work to make things work their way. I have a PHP app that I rigged up using Vue.js. Took two days to do. Had to change nothing in the app, instead of rendering views with PHP they are output using JSON simple enough. Powerful. Can't do that with Angular for sure. Don't have time to deal with react and its nuances.
This, a thousand times this. I strongly considered Vue for a recent project but needed a bit more and went with Aureli, and now that it's out of beta I hope they keep up their rapid improvements to the docs to win over people with simplicity in getting up and running with Aurelia.
What does "want you to do things their way" even mean? Aren't you doing things a certain way by virtue of using a framework? Maybe angular/react is just making you do things in a way that you prefer not to, while vue.js is making you do things in a way that you find reasonable. For other people, it's the reverse.
If you have to do things in a specific way, then you are forced to learn that at the same time as you are learning the technology. Learning just vue on the other hand, is much easier when you can retrofit your existing knowledge into it. Then worry about the 'proper way' later when you have made your first few apps. I already have boatloads of knowledge, and whilst it may not be '2016', it's been good enough for the past 5 years.
React on the other hand, whilst it gets described as 'just the view', but I haven't seen a single tutorial that uses anything other than React/Redux to drive it.
To even get started in React, you need a babel, npm, gulp or webpack, node and a data-store of your choice. On top of this, any of the tutorials you can find from a full-stack perspective get made obsolete within months. This is javascript fatigue, all you have to do is look at this recent article.
It makes me wonder how many 'npm install' developers actually understand what is happening under the hood. This is not worse than the DOM ignorance that jQuery causes IMHO.
> To even get started in React, you need a babel, npm, gulp or webpack, node and a data-store of your choice
This is patently not true. You don't need any of that to make a React app -- you can just download the min.js files and get coding. React is perfectly capable of handling it's own state management and webpack/babel/npm are just to make your life easy. The problem is people follow full-stack, real-world tutorials like the one you linked without first just learning React.
> React on the other hand, whilst it gets described as 'just the view', but I haven't seen a single tutorial that uses anything other than React/Redux to drive it.
As a former Angular dev gone React, I've been able to accomplish 90% of what I could do in Angular, using React, React Router and Fetch API.
> To even get started in React, you need a babel, npm, gulp or webpack, node and a data-store of your choice.
Create React App allow you to forget about that stuff and just worry about your app. Same with Next by Zeit, and there are plenty of other things including a couple of CDN backed script tags you can throw on any html page and start using React right away to get started.
> On top of this, any of the tutorials you can find from a full-stack perspective get made obsolete within months.
That's because all these boilerplates or tutorials are pushing a style of developing React apps in which that specific person finds the best way.
> This is javascript fatigue, all you have to do is look at this recent article.
JavaScript fatigue is result of lacking knowledge of the basis of the JavaScript language and feeling you need to use the next greatest shiny framework and misunderstood boilerplate to "get up and running quickly" with said new shiny without a grasp of the tools used causing them to break and you not knowing how to fix it.
React uses JavaScript that everyone should know and be able to apply to anything else to do stuff.
You're not extending a special snowflake "class" system that requires you to do things drastically different from previous "class extending libs"
Because of this, tools like Inferno and Preact can prosper and allow users to literally swap out using React for Preact in production just by setting an alias in Webpack.
There's no special snowflake syndrome, JSX is just a syntax ontop of JavaScript to make it feel like we're writing HTML (with a couple caveats), but you don't need to use JSX. You can accomplish the same thing writing React.creatElement calls, as it's just props all the way down.
JSX is also compiled at build time, and not at runtime. You may think this is a problem, but lets be perfectly honest, most people already use tools like SASS/LESS and have a build step in their workflow already, adding another one isn't complicated.
Maybe it's origins too. React and Angular are massive and high marketing products. The viral spread is organic but not self emergent, unlike vue where users kept going back to it and talk about it naturally; because it's "good enough" and more humane in it's structure and interface.
Is there a Vue Native project of some sort? Currently planning on using React for a new project strictly because I can use the same components for a native app on multiple platforms.
Technically not yet, but from the official Vue 2.0 release announcement:
> we have started an official collaboration to make Vue 2.0 the actual JavaScript runtime framework for Weex. This will enable users to write universal Vue components that can be reused across Web, iOS and Android! The collaboration is still in early stages, but it will be a big focus for us now that 2.0 is out, so stay tuned!
He also has wonderful documentation, and the framework itself makes it easy to move code over from angular 1.x. The give a shit factor is huge when you look at the quality of documentation and the website organization. Just telling people to "read the code" doesn't cut it, Even hit a home run with the quality of his project website and documentation.
I wouldn’t say React is “hacked together”. Perhaps you are referring to the React ecosystem? Facebook doesn’t build single-page apps with React, so naturally it doesn’t provide solutions for routing and similar concerns, so there is more churn as people are figuring this out together.
I use React all the time for individual components on server-rendered pages. It feels like a natural extension to formerly monolithic Rails/Node/etc apps.
That said, when an SPA is called for I'd far rather use Ember and get routing, state and a hundred other things for free, without needing to bolt together an entire front-end framework from parts each time.
Absolutely! I'm current using it for a entirely back-end routed Symfony app. It's perfect for any front-end stuff complex enough that jQuery would become a mess.
I completely disagree. Vue seems like a step backwards for me -- it does very little that I couldn't do with Backbone/Marionette. I don't want templates, I don't want data-binding, and I DEFINITELY don't want opaque directives in my HTML.
A good place to start a comparison is when using Vue.js in production looked viable - the October 2015 V1.0 release. At that point Angular has amassed 46k github stars, React had 35k.
Star counts don't tell us everything but they're an OK heuristic of how many people are invested in a library at a point in time. Had Vue.js been in anyway meh it wouldn't have made such a dent in people's attention.
Timing luck, insofar as it exists, is probably weighted towards arriving later. Vue had a chance to listen to the market and solve some of the headaches that developers were voicing about incumbents. V2.0 is basically the best bits of Angular and React.
Angular was released in 2010. Vue was released in 2014. Bit weird to call it "pretty old", and Angular was well established by then - they announced the v2 preview around the same time.
2014 was the year Angular "really took off" and 2015 was the year React "really took off" (at least, if we trust "Google Trends")
Vue is, in its core, very similar to Knockout (which I think is pretty swell). I think coupled with a better DOM abstraction (like React) it can do great thing - that's what MobX does and why I like it.
I sympathize with the post's sentiment of giving UI people work.
It was around, but I don't think it was as mature. At the time React was becoming viable, I recall the VueJS api being pretty unstable (e.g. functionality being added in, then removed, then added back in, basic patterns being completely changed, etc).
I've used Vue pretty much daily over the last year in a fairly complex app (some 150+ components, Vuex store with 100+ actions, full client side router navigation) and it has been pretty pleasant. I even contribute a nominal amount to the Patreon campaign.
However, the upgrade path from v1 to v2 is not a quick undertaking. Certain changes require a revisit to practically all components (e.g. change of 'ready' to 'mounted', v-el to ref etc.) that don't really bring a lot of value to the end user other than change in semantics. The upgrade diagnostic tool is a great feature, but seeing 600+ breaks in your app is not so much fun. Changes in Vuex (e.g. no more vuex: getters in the components, 'dispatch' is now 'commit' in the store modules) translates to significant work in a largish app just to upgrade semantics.
Also, the article references the verbosity of Redux with respect to forms. In all fairness, all Flux implementations, including Vuex, have pretty much similar verbosity.
Just providing some balancing thoughts for folks to be aware of before investing heavy time in any framework, including this one.
One of our engineers at StackShare[0] suggested it and it's fantastic.
Mobx is very simple to understand and will make writing a "React" page a real joy again. Redux was way too complicated for what it gave, and just shot term after term after term at me that left me with a headache. I still don't understand Redux proper.
>Why do you have to type so much?
I know! I nope'd away from Redux because of that same reason.
But Mobx clicked for me. And if it clicked for me, it'll click for you.
Basically you have a store and you use that store anywhere in your components to share store state. When you update that store state everywhere else updates as well. Simple.
Another great reason to use React as opposed to alternatives is react-native. A _lot_ of knowledge transfer between the web and mobile with react native. It's pretty insane.
I agree 100%, MobX is like a full order of magnitude performance upgrade for me over redux.
You can just think of it as "automatix redux + reselect".
People think they use redux for immutability but in my experience most people just use it for updating the view when the store changes and end up with a lot of denormalization and stale state.
With redux you derive as much state as possible which is great.
If you have a property you need observed - add a `@observable`.
If you have a react component you want to update automatically, add `@observer`.
Derive as much as you can using `@computed`. You can but shouldn't use `autorun` which monitors side effects.
If you're already used to Vue it's very similar except it works with React.
That's pretty much it - just clone a boilerplate - the API surface is _tiny_ and everything "just works". I have a hard time describing how stupid I felt for using Redux after playing with MobX for 10-20 minutes.
I get the feeling that the terms "easy" and "simple" are being mixed up here. MobX is a lot more complex than Redux (core), as it tries to do a lot more things that are braided together as a package. In Redux you choose to bring in that complexity (reselect, redux-saga, etc) if necessary. "Easy" is subjective, "simple" is not.
> MobX is a lot more complex than Redux (core) [...] In Redux you choose to bring in that complexity (reselect, redux-saga, etc) if necessary.
I've dug quite a bit into Redux and I don't think that's really true. In particular I don't think you "choose" to bring in that complexity. Redux is inherently complex the moment you add async actions to it, which (in my view) any real Redux app will need. Something as simple as "fetching some data when you click a button" is a surprisingly elaborate process. Similarly, trying to map a large state tree (which any real Redux app will have) to a component tree is not easy. Libraries like reselect and redux-saga (or event redux-thunk) sprung up and became essentially universal because they address the inherent complexity of Redux.
I just don't think it makes sense to tease out a small chunk of the code a Redux app needs to function and say "look, this chunk is small!"; it's true but meaningless.
MobX is dead simple, it's a short write and here's how it works:
- observables: add a getter/setter pair in place of the property - when it gets modified emit an event.
- observer: when an observable getter gets called inside the `render` in React - listen to future updates and re-render.
- computed: do the same thing as observer - but emit the value instead of rendering.
All MobX does is change detection, it has a very low API surface, it can be implement in a lot less code (but optimizes heavily) and it is one of the simplest packages I worked with without middlewares and connectors and selectors and so on.
In Redux you have a dispatcher, actions, a reducer and so on. In MobX you just have plain JavaScript objects for state and plain functions. MobX also composes much better with things like Rx.
Except it is. I have worked on a couple of react/redux production projects and they all work well, but I still think redux is way too convoluted for most use cases. Too many abstract concepts.
Also their naming of the features could have been better. For example "reducer" makes sense ONLY after you understand what's going on. It should be the other way around--the naming should be intuitive enough to actually help me understand the concept easier.
A lot of physics theories are distilled down to a single equation, but that doesn't mean it's simple concept to understand. I personally think a library with 10000 lines of code that operate using setters and getters is much more simple to understand than a library with 100 lines of code that has all these esoteric concepts.
It looked "magical" and tripped up my "too good to be true and I'll have problems later" sensor. Then I looked at that video and realised the idea is rather simple and brilliant.
Ok, so I think I understand how MobX works. What I don't understand is how this is different from just having a global handler updateStore that runs a forceUpdate() on the root component. You set todo.done = true somewhere down the line and run updateStore. It will re-render everything and change wherever todo.done is used.
There is a valid criticism at the core here, that the JS community jumped a bit too quick on Redux/Flux. Even the author of Redux said quite a few times now that you should not blindly use Redux, but only if you see an actual need for it.
I liked Redux when I experimented with it, but it is not a panacea, the advantages you gain are not entirely for free, and it might not be worth the boilerplate and complexity if you don't have a very complex application.
You can use React vanilla if you want, but you will spend a lot of time keeping props in sync and making sure changes are invoked up the chain.
So cool, you nailed that down vanilla - you're awesome.
Or you can just Mobx and not worry about it.
It's not like you're forced to use Mobx. Even when I worked with Windows Forms in .NET 2.0 you still had to have some way to keep values in sync, and instead of "Mobx" you had some home-grown monstrosity.
I'm a designer and not a coder, so I feel obliged to provide my comments with salt added up front.
That being said, JSX vs. wrapping HTML in if-statements seems like the same kind of trouble to me. I've done a few simple prototypes in Clojure/Script, so my reasoning is heavily influenced by the fact that I know very little about other languages, and only have moderate amount of knowledge about Clojure.
The solution I've encountered in Clojure is to represent the entire page as a data structure. Conditionals and transformations are applied directly to this data structure, which is then sent as-is into the rendering pipeline (which commonly seems to be React). The HTML is never really written by hand, it's just a final "coat of paint" on top of the data.
To me, this seems far easier to wrap my head around than splicing two languages together in the same file and potentially finding that the interaction between the two is not as harmonious as one may wish.
Rendering to HTML, rather than rendering within HTML (so to speak), seems like it would remove the entire decision point where you have to pick between one library or the other based on the quirks of how it looks when it's spliced into HTML.
I feel that a certain amount of humility is due when commenting on a field of study that's not my own. I know that there are many—particularly here, most likely—who have thought far longer and harder about these problems than I have.
Edit: by the way, the reason I picked up Clojure is because I (for some reason) watched Rich Hickey's talk Simple Made Easy and thought to myself, "hey, that person is thinking of programming in the same way that I think about design." I felt that the design principles he described that guided the development of Clojure were very similar to a lot of things I've come to consider when designing for human interaction. So I thought that by learning Clojure I might become a better designer, even though I don't write code professionally.
After programming for many years I found Clojure pretty mind-bending, so definitely props for being able to pick it up.
Clojure 100% made me a better programmer. I got pretty in to it for a while but ended up punting and going back to React, and then later Vue, because I really started to feel like the "code is data" thing makes the code really hard to understand at a glance.
Example: in Reagent (this applies to all of the react-wrappers I think), displaying a table is as simple as returning a vector in a certain format; thus my code is a simple function mapping what I have (probably a vector of maps) to what Reagent wants.
Simple. Mathematical. But here's the thing - my brain doesn't work in functions that transform data. Instead, I'm trying to think in HTML, because that's the target result anyway. So I have to kind of parse the code mentally and mentally compile it to what it will "really" look like. Maybe I didn't work with it long enough to get used to it or something, though.
JSX, Vue, Angular really help with that mental compilation step and allow you to see something a lot closer to what's going to be actually output, and therefore make it a lot easier to reason about what the browser's gonna do.
Anyway, I was curious, have you continued working with Clojure very much?
That is what React does, though: you write your page using a data structure (in JSX, an XML-based DSL, or you can use the createElement function directly), and then the React engine parses, diffs and renders your data structure into the DOM. This was React's most touted advantage at the beginning: you write what you know (JavaScript), and React handle's the tricky DOM stuff. JSX isn't templates, it's JavaScript.
Clojure(Script) benefits greatly from the fact that Clojure's data structures are much more expressive and robust than JavaScript's, and so a thing like JSX that paints over some of the language's warts is less necessary.
Many people opt for using something like virtual-dom or snabbdom instead, which provide a more Hiccup-like API on a surface level. There are wrappers for React (react-hyperscript) as well.
Can you tell me what clojure libraries/frameworks work the way you describe? I'm learning clojure and would like to build some toy web apps because I've never done webdev before.
Start with Figwheel[1] to enable hot-loading code and live reloading:
lein new figwheel <app-name>
I have used Reagent[2] since I'm only doing prototypes and don't have to worry about production quality. Om/Om Next[3] seems like it would be worth checking out since it does a bunch of clever things that Reagent doesn't. Reagent is very straightforward and therefore might be the better starting point, seeing as you're just starting out.
Like the sibling comment pointed out, Reagent uses Hiccup-style data structures to represent HTML. Om can be configured to do the same, but doesn't out of the box last time I checked. Either way, the Hiccup syntax looks like this:
[:div [:h1 "Hello world"]]
It's just regular arrays with symbols, strings and what-have-you, meaning you can construct them using standard Clojure functions in any way you see fit.
Add either Reagent or Om to your project.clj, and off you go.
Definitely try it sooner rather than later, it's good stuff. I feel like re-frame is what you would get if you put the time into selecting the best libraries to integrate with React, and then removed as much boilerplate as possible.
I believe React is popular (among other reasons) because you don't need to learn what is v-if v-else and other repeative commands when you have plain and simple JS equivalents.
React has te philosophy "It jusy works", and people love this
Yes, I think the main selling point of React is it's tiny and intuitive API.
I don't know how these frameworks compare in bigger sized applications, but if you just do a POC in Angular2, React and Vue.js, then React beats all of them. This probably leads to many people considering React for their new applications.
If you go for bigger stuff, I don't know which would be better. I like React, but I also found it a bit cumbersome to create all these Redux actions and stores etc. Also async stuff, especially righ datarate websocket stuff, seem a bit awkward with Redux.
Got numbers? I know someone who was able to get a simple app down to below 30kb including polyfills (albeit with a lot of work using Google Closure), and from what I understand that was before AoT compilation was there.
Much of the core is shakeable, I don't believe your assertion at all. As you use more features, the app size would grow would be true due to using parts that were previously shakeable becoming unshakable, but that complexity being in a unified language/base of a framework worked on by very smart people is most of the time better than homebrewed business logic by an above average developer
Any developer familiar with mustache templates, Backbone and/or Angular should immediately pick up Vuejs templating. For me and most others I've heard from, the cognitive overhead was minimal.
If you prefer html templates you're going to choose a framework like Vue, Angular or Svelte. If you prefer Javascript driving the show you'll be more comfortable with something like React. The two approaches are duals of each other.
Personally I prefer an all JS solution because it's better suited to handle conditions and loops as compared to using custom SGML markup with framework-specific tags and attributes. In my opinion SGML/XML should only be used for markup, not program logic.
There are a few things I think React got wrong though - handling of children being one. Having different code paths to handle a single child versus multiple children was a design mistake. The Children convenience module is awkward to use. The state life cycle and immutability in React takes a while to get used to. It does seem more complicated than it needs to be and has spawned a plethora of React state management add ons.
I agree about conditionals and other kind of programming language constructs not belonging in markup. But the point of markup for content-driven web sites is that its a text format and can be contributed by persons other than web developers (authors, site users, syndicated content providers, etc).
You can see a modern approach for this is at work here: http://sgmljs.net/docs/sgmlweb.html ("isomorphic" rendering to HTML in the browser and server-side using full SGML, no less).
Our company migrated to vue.js, 6 months ago. Our complex app is messy with JSX, router, and new dev can't keep up with code. Now we start every new app with Vue.js. The gap between junior dev and senior dev comes closer. They can collaborate with less bugs, less problems and less time to develop.
Interesting. I'm also looking at Vue.js and wondering how it can benefit me. Just one thing that I want to know: how do you do checks and tests in it? Are there any frameworks or tools to do that?
> Fun fact: Yii was created by a Chinese speaking guy - Qiang Xue. So, you might call Yii+Vue stack not just very difficult to pronounce, but also a Chinese stack :)
Fun fact: Qiang Xue got his PhD at Duke University and developed Yii2 while living in the D.C. Area by leading a multi-national team of core contributors, the top 3 being from Germany, Russia, and Ukraine.
He also moved on from the project mid-2015 and the other maintainers have run day-to-day operations since then. It's not a "Chinese stack". I've read the source and issues extensively and it is high quality code that welcomes high quality contributions - no matter where people are from.
I think it's disingenuous to claim so stridently that it isn't a Chinese stack (not to mention the implicit assumption that Chinese code is not composed of high quality contributions). They're not saying that it was solely Chinese contributors who made it, just that the originators of Yii and Vue are Chinese. Yii and Vue can be considered "Chinese" in the same sense that American founders that come out of HAX Accelerator[0] in Shenzhen and operate primarily in China could still be considered to have created "American" products and companies.
I was never trying to put anything negative into this statement that both these bright people are Chinese-speaking. I know they both live in US (though it might be unfortunate for us that Qiang is currently doing Go programming in Capital One instead of actively developing Yii2). Yii2 and Vue.js are top notch.
I didn't so much read it as a negative, it's just that readers unfamiliar with the projects may think that "Chinese stack" means 1) code/issues are in Chinese and/or 2) the main contributor base is located in China.
I've been a long time user of Yii1 and Yii2. Qiang has created 3 PHP Frameworks between 2004-2015: PRADO, Yii1, and Yii2. At one point he was on a >700 day commit streak with work on Yii2. I can't blame him for needing to focus on his own professional career - OSS doesn't always pay the bills and can be very demanding.
I agree with you, and I definitely do not blame Qiang on choosing his way. I just miss him as Yii2 contributor and visionaire because that could make a real competitor to Laravel some day, in terms of community, and popularity across US and Europe. Right now Yii2 seems to move in direction of becoming a niche framework for Eastern Europe and parts of China, instead.
I agree, I miss Qiang's visionary leadership on the project also. Given his history of building frameworks I'd say there's a good chance of him doing another. It may not be PHP next time, though.
I wonder if Yii2 adoption moving more towards Eastern Europe and China is more a macro trend of PHP in general. I feel like US firms are typically choosing other languages when starting new projects based off postings and job boards I've seen recently. Maybe my view is tainted from reading too much HN though, PHP doesn't get much love here...
Drupal is a bit overkill for a blog-like site, my impression is that it is usually used for more complex sites than e.g. Wordpress.
With the latest version Drupal 8 there also was a push to make headless Drupal easier, which is pretty much just the Drupal data exposed as an API so that you can create SPAs for it.
More complex, sure. But it's still very centered around taxonomy with dates/sections, end user editing of nodes with WYSIWYG, page centric tags, etc. Very blog like.
Seems like a big hammer for use as a datastore for an SPA.
Drupal 7 and 8 use entities, which are arbitrary combinations of fields that can be composed through the UI and accessed through APIs via JS or other methods.
One thing we use it for is its user management which is good enough out of the box.
Yes. And you could produce that with wordpress as well using custom post types, with probably a similar amount of headache. They are both CMS systems that primarily handle taxonomy, nodes, tags, WYSIWYG editing, etc.
Out of curiosity, one reason the author mentions (and I know, it's not his selling point) which I've seen others reiterate is that React's render() method doesn't support if statements. I know you can write something like the code below in React, so what exactly does that criticism refer to?
function Home(props) {
return (
<div>
<h2>HELLO</h2>
<p>Duis a turpis sed lacus dapibus elementum sed eu lectus.</p>
{ (() => {
if (props.location.query.home) {
return ( <p>You specified a home query: { props.location.query.home }</p> );
}
else {
return ( <p>No home query was specified.</p> );
}
})()}
</div>
);
}
To be fair, writing if statements in JSX is messier than it should be, but this is the fault of JavaScript and not JSX. If statements don't return anything, so we have to either create an immediately executed anonymous function (like you showed) or use a ternary operator. I'm pretty sure the author knows that you can put if statements in JSX but is frustrated that it requires boilerplate, which I think is a valid criticism. That being said, I greatly prefer using plain JavaScript over custom DSLs like Mustache.
I can see that. I just wasn't sure, because every time a React debate gets kicked off, I inevitably see the "doesn't support if-else" thing get brought up, and having finally worked through a MWE with it, wasn't sure if it was just the (somewhat) convoluted syntax or whether I was missing something bigger.
Yeah, it's possible in React do to it. But compare that to how Vue handles conditionals:
<template>
<div>
<h2>HELLO</h2>
<p>Duis a turpis sed lacus dapibus elementum sed eu lectus.</p>
<p v-if="location.query.home">You specified a home query: {{location.query.home}}</p>
<p v-else>No home query was specified </p>
</div>
</template>
I don't know about you, but to me this code is 100% more readable than the React example you gave.
This is how I've come to write that in React, after giving up on attempting to find a consistent way to write ternaries which I would find acceptable when revisiting them (it just never happened):
let Home = ({location}) => <div>
<h2>HELLO</h2>
<p>Duis a turpis sed lacus dapibus elementum sed eu lectus.</p>
{!location.query.home && <p>No home query was specified.</p>}
{location.query.home && <p>You specified a home query: {location.query.home}</p>}
</div>
I usually put all the possible negative cases first because outside of micro-snippets they tend to be short and sweet compared to the positive condition.
It's strange to me to embed conditions in attributes - particularly the v-else case in a different tag. It requires several visual scans of the block of code to determine what's going on.
In my opinion the following requires less cognitive overhead:
function Home(props) {
var query = props.location.query.home ?
( <p>You specified a home query: { props.location.query.home }</p> )
: ( <p>No home query was specified.</p> );
return (
<div>
<h2>HELLO</h2>
<p>Duis a turpis sed lacus dapibus elementum sed eu lectus.</p>
{query}
</div>
);
}
function Home(props) {
return (
<div>
<h2>HELLO</h2>
<p>Duis a turpis sed lacus dapibus elementum sed eu lectus.</p>
{
props.location.query.home ?
( <p>You specified a home query: { props.location.query.home }</p> )
: ( <p>No home query was specified.</p> )
}
</div>
);
}
What bothers me about this and other templating is that branching is so inconspicuous and therefore hides its complexity
.
Lets takes this extended example:
<template>
<div>
<h2 class="c-section-heading">HELLO</h2>
<p>Duis a turpis sed lacus dapibus elementum sed eu lectus.</p>
<p v-if="location.query.home">You specified a home query: {{location.query.home}}</p>
<a v-else v-on:click="specifyHomeQuery" class="u-warn">No home query was specified</a>
</div>
</template>
And compare it to:
<template>
<div>
<h2 class="c-section-heading">HELLO</h2>
<p>Duis a turpis sed lacus dapibus elementum sed eu lectus.</p>
<p>You specified a home query: {{location.query.home}}</p>
<a v-on:click="specifyHomeQuery" class="u-warn">No home query was specified</a>
</div>
</template>
The first one creates a div with 3 children with the type of the last one depending on the condition. The second one creates a div with 4 children (and a warning in the dev console). Both have 4 lines between the <div> with the same content except for two attributes on two elements and are indented the same by convention of the framework. They look nearly identical when quickly parsing over them but results are very different.
Compare this to the other react solutions, or my personal favorite:
const Home = ({location}) => <div>
<h2 className="c-section-heading">HELLO</h2>
<p>Duis a turpis sed lacus dapibus elementum sed eu lectus.</p>
{location.query.home
? <p>You specified a home query: {location.query.home}</p>
: <a onClick={specifyHomeQuery} className="u-warn">No home query was specified.</a>}
</div>
I think it's pretty clear which "templating system" better represents the fact that this has more complexity than just a simple, linear component.
Mixing tag and conditionals in attributes is so messy, I don't know how people accept that. It messes with the level of the scope, you can't quickly see that only one of the <p> will be outputted.
Although I am admittedly fairly green when it comes to using React (full disclosure, I use Flux to manage state), I am unsure as to why you would NEED or want to handle conditional forks within the view itself.
My understanding of React was that conditions such as this should be handled by whatever is managing the state of the component, be it a method call within your view that alters your the local state, or a store based system such as Flux/Redux where the state is handled outside the view itself. Part of what makes React a beautiful framework (to me) is the concept of a state which controls what is rendered. Controlling what is rendered directly from the render method in the view seems to defeat one of the purposes of using a stately framework such as React in the first place. Sort of a cart-leading-the-horse situation.
Again, though, I am new to this framework (and JS frontend development in general) so please feel free to correct me.
I hope I don't get downvoted for asking this but is React going out of fashion already? A lot of the talk about it was "React is here to stay" or "React is as permanent as JS itself" but now this is the second or third time people seem to be going for Vue instead. What happened?
"We've been using React for a year and will continue to do so" isn't an article that gets written often, despite there being more people in that boat than switching to Vue.
React is in no way losing popularity. It's just not as interesting to write about something everyone agrees on. That said, React won't be around forever - very little ever is.
I think React will be around for a long time. Vue.js may also be an indication that React was on to something, fundamentally. So I wouldn't think of it as heartbreaking that Vue.js is making an impression using some of the same design patterns as React. Javascript framework design may just be converging on an overall theme, with competitive variations. Last I heard, Vue was even working on JSX support.
React is about the only real framework in the ClojureScript community, via frameworks like Om.Next and Reframe. React in JS is rather clunky since you're dealing with a mutable language that prefers OOP primitives. In ClojureScript most UIs are data-driven and declarative and that's where the strengths of React really shine. So I would argue that ClojureScript turned React into a better React.
React as it is now isn't going to be React as it is at some future date, it will evolve. Any framework you use has an inherent risk of going stale and being replaced by the next new new thing. Luckily, to get stuff done, you don't need to be using the new new thing, so choose your frameworks based on whether it makes sense for your scenario. Jquery / UI was the rage at one stage, and it still chugs along.
React isn't the only game in town... some other popular ones are :-
Vue
Angular
Elm
All of them have a certain amount of momentum which means, for the short to mid term they are going to be hanging around. But they all have inherent tech risks going forward. It only takes a few innovations browser front end wise to be mainstream to make newer frameworks become the new new thing. For instance things like webassembly / more GUI / vector based GPU accelerated capabilities opens up new ways of putting together apps using all kinds of languages.
I can't see React going away soon. It really does work well, and a lot of the author's problems aren't not unsolvable problems. Some are so easy to solve that many people probably never thought of them as problems (Micro components and forms have never been an issue for me.) The only real issue that I agree about is the excessive typing, but that seems like an adequate trade-off. His complaints about pure functions and immutability seem strange to me, because these aren't abstract concepts that neckbeards like in order to appear smart, they actually make programming easier. My team (about 15 front end devs) built an extremely large, complex app in a relatively short amount of time with React, and it's scaled surprisingly well. At scale, it's not easy, but that's because any huge app is going to be difficult to build.
Yeah, we recently had a co-worker complain about immutability ("it just exists to be a pain in my ass"). I asked to examine his code and sure enough, pointed out that if he mutated the variable it would have created bugs in other chunks of code.
Who cares? Fashion is not an engineering criteria, you shouldn't be factoring fashion into the question of whether or not a given tool is the right one for the job.
> A lot of the talk about it was "React is here to stay"
Unless Facebook has announced that they are abandoning React, this statement is as true as it ever was at any point in time.
I think fashion does come into the equation if only because it will be easier to find people who can grok the code base faster since they understand the framework and common idioms associated with it.
Where I work, we just had a bunch of new hires and they're being productive within the first couple weeks because they know React, and our app uses React Native.
React-knowledgeable devs are in high demand right now, which drives smart devs to learn it and garner experience with it, which makes it more desirable to use as a tool in your stack.
I disagree. The cost of onboarding a new developer is negligible compared to the cost of picking the wrong stack for a project just because it might be the hippest tool at the time. An experienced programmer can pick up a new framework in a week or two tops and their ability to pick up the application code will have more to do with the quality and documentation of said code than anything else, but if you pick the wrong framework you'll be paying for it for the life of the project (or until you refactor with a new framework and write a blog post about why you decided to switch).
If the tools you're using cause your code to be inherently difficult to grok, then that is an engineering problem, but that has nothing to do with how fashionable the tool might be.
I think the pendulum will keep swinging between the minimalists (React/Vue.js) and the frameworks (Ember/Angular).
Ember is completely underrated and overshadowed by React right now. It takes some of the best ideas from React (components, shadow DOM, FastBoot) and puts them in a cohesive framework that has an incredible support ecosystem and upgrade path.
To me, it's the reintroduction of custom templating. I appreciate E4X/JSX syntax because it's just a thin layer of sugar which is compiled to regular JS syntax. It also lacks custom implementations of loops etc, requiring the user to write _Javascript_ not some non-standard templating language.
It has been quite some time since I started writing front end code, tried understanding angular, left it. I was lucky that I came across Vue.JS via HN, it was gitlab's post. I haven't ever tried React, because Vue is amazing. With nearly no knowledge of JS, I was able to write an app in Vue reading just the official docs, they are downright amazing. I faced the issue of webpack et al, thus I started writing a guide to write vue apps in vanilla JS,
Thanks for posting. I've just had a quick glance over the first chapter of your book and I like the simple approach you take to explaining the core elements of vue.js and SPAs.
Vuejs looks great for POCs or small projects. It feels better like Angular-1 to start with. I use VueJs a lot for small stuff i.e. usually something that I can fit into one index.html file and forget about it. React killed that simplicity (i.e. stopped supporting it). Angular2 - I can't figure out why anybody uses that.
But when it comes to larger projects - I still go back to React, TypeScript and Redux. While Vuejs makes it simpler to code, React+TS+Redux make the end-product very much reliable.
One small point to add here. Evan You is a pretty amazing individual, but he is no longer alone. There is a core team of six members.
I know because the guy who got me interested in Vue.js, Chris V. Fritz, lives in the Lansing, Michigan area and is responsible for the excellent docs on Vue.
I haven't been able to locate a list online but I know there's a core member in Paris and another one in Japan.
I would recommend Cx to anyone building complex forms. It's one package that covers all common problems related to forms - validation, data-binding, multi-value lookup fields, horizontal form layout, theming etc.
The author says they don't like purity and immutability, because it limits their ability to "get stuff done". But in the long run you get many benefits, whether you have 1000 developers or one. Namely that a whole class of bugs will be eliminated and you can do quick reference comparisons to tell if something changed.
Every time I go to look at Vue I can't stand the fact that it DOESN'T have JSX. I've used every template system you can think of and they always fall apart when things get hard.
JSX is basically JavaScript but a much easier and nicer syntax (basically HTML).
You get the same flexibility with Elm, but even there you don't get the nice JSX syntax:
ul [class "grocery-list"]
[ li [] [text "Pamplemousse"]
, li [] [text "Ananas"]
, li [] [text "Jus d'orange"]
]
The one criticism I happen to agree with is certain aspects of using forms in React. Checkboxes and radio buttons are pretty buggy and stupid. Kind of unacceptable at this point.
Not sure what you mean by "legit use case", because you could write just about anything in vanilla, but for React specifically the value of using it comes from state management.
By explicitly defining what is state and when you change it the application becomes largely pure/functional and this has a tendency to both decrease bugs and make the application easier to reason about.
You could do that in Vanilla as well, but as your apps grow React or whatever.js generally is ready to grow with you, whereas your homebrew solution may not be.
Really good framework indeed. One of the few who are really good in handling realtime data. Its dataflow-components are much more flexible than React components, which makes it really more flexible.
I stumbled across Cycle.js a few weeks ago. I like the idea, but the examples still seemed a little clumsy.
I would like something similar, but a little more opinionated, with some shortcuts for booting up a simple project that sprinkles some "magic markup" in an existing page to drive a backend event handler / mapper-reducer function.
I'm not sold on the whole "code quality" vs "getting things done" mentality here.
I think there are diminishing returns in reducing technical debt and keeping a high quality codebase, but the point of doing it that you can maintain a sustained, relatively high "getting things done" rate over the project's lifetime. There are times where you should implement something in a quick and easy way, but if code is going to be present and important for a long time then going the extra mile usually pays off.
It was as simple as adding Vue.js itself and one JS file for custom code. I tried using Angular but right off the bat, I had to install hundreds of dependencies via NPM.
That's what I like about Vue.js. It's simple to reason about for the kind of use case I linked above.
The arguments against Redux (which this article doesn't really make, but still) are very valid - it is a nice abstraction and way to think about data flow, but its simply too much boilerplate.
Almost every Redux example is tons of repetitive code because of this, and that's before you add in middleware, thunk, saga, reselect etc. Yes I know Dan himself wrote a bunch of articles on how you don't really need to use it and how its conceptually simple, none of that changes what most of the libs and code looks like.
I don't have the answer but I can't help but think there has to be a better way to handle this. We had templates and generics decades ago exactly to reduce repetitive boilerplate.
Redux should never have been adopted in its current form. Its exactly the sort of thing that should be handled by a framework/tooling for you. Imagine if for every React component you had to write a custom parser/resolver/reconciler, all of which had 99% common code and just passed params around. That's what redux boils down to.
Thanks for the detailed write up and comparisons. Also kudos for not bashing other frameworks and giving a level headed comparison.
Two big things I noticed that drove you away from react.
1) too many subcomponents:
I think jsx can be improved to have logic tags within them. E.g <js:for> and <js:if> tags that the transpiler can move to ternery and array map calls.
2) too much verbosity: something like mobx or deep-observable can help here.
Honestly react has become the Java of UI. Going back to fundamentals. All you need is a tiny library that diffs a vdom tree to real dom.
And you need a tiny library that allows you to observe a single source of truth object and connect it to view.update() changes.
All in all this shouldn't take more than 5kb of code.
We all want: good abstractions, fast performance, actionable errors and small library so the page loads in no time.
Vue JS framework is very simple yet powerful, also better in performance wise. Learning curve is very easy. You can pick the fundamentals in a day or two. Within a week you can reach intermediate level.
It comes with all the basic stuff of SPA like data binding, event handling, routing, state management, components.
I have been creating a video tutorials series on Vue js 2 framework.
what I always wanted how many Vue instances do I need for a SPA?
Do I just export every javascript object and register them globally? how does Vue.JS work with DI?
I find it completely unbearable to use React with plain JS. I have to use at least Coffeescript and if possible Livescript or Clojurescript. Vanilla JS is just too clunky.
The problem with JS is there are too many patterns in the code, like the mentioned list.map(function(whatever) { ... }). Because JS is a medium power language it doesn't let you abstract this stuff with macros or at least rewrite the syntax.
Coffee and Live provide some relief, but Clojurescript is heaven.
While this is a good overview of why _they_ chose Vue over React, I wouldn't risk deriving that you should do the same too.
To balance the scale a bit, this is what they gave up, in favor of "shit that just works" (because this is the tone I'm getting from the article):
1. They decided they want off the enormous driving force for developer experience that is Facebook, and more importantly the Facebook codebase that shapes decisions in React, see [1] and [2].
2. They opted out of major innovation that directly stem from (1), see [3].
3. Parting with Redux, they also decided to part with a community that thinks functionally. This is a big deal not because of writing "pure functional code", but because these group of people can reason about the implications of bad citizenship on the browser - which really, is something the Javascript community really needs.
4. Moving away from functional-esque (for lack of a better term), they also move away from predictable testing. Forget purity and sideeffects. A good litmus test - think about how easy it is to test any given framework at scale, and if a framework is "built with testing in mind" (read: angular) how many hacks would be involved. When you have good foundations for testing, you can do this [6] and be sure everything can be covered [7] .
The only thing I see as a down side with React is the bundle size. The physical size. However I'm not worried one bit because of (1) and (2).
For Redux, I take the liberty to use MobX for small-medium projects (which probably is the overwhelming majority of projects), and Redux for large projects, or projects that I want great testing story in (in many ways these correlate, but some times they don't).
Redux is "boilerplatey" because it is highly granular. This is why the ecosystem around it exploded. But because of (3) the ecosystem around it has a sharp focus around the patterns and practices it applies, which makes choosing the "wrong" library not such a big deal; in a sense its ecosystem is predictable, because it is simple.
JSX or templates, I don't think this deserve a major part of the discussion. Both ideas exists for a long while, and even their predecessors exist for more than a few decades [4] and [5]. I don't think anyone is tilting the scales any where in a major way. I personally am convinced JSX is a new thing because you have first-class IDE support across the board (which you don't have for a given data-properties backed templating language unless it becomes ginormous like Angular). JSX is also simple to hack and you can opt-out or implement your own dumb-templating solution-to-JSX.
Having said that, I see Vue coupled with PHP quite a bit, like, it's an informal standard stack, so it may make sense if you're coming from PHP (but then again so did Facebook, right?). Maybe someone can explain that (is it the Laravel backing?).
I think your opinion on putting weird stuff in your HTML attributes vs. putting weird HTML-like stuff in your JavaScript is enough to make an early call on whether you'll prefer React-like libraries or Vue-like libraries.
As a programmer, React has been my go-to UI library for quite a while because I see always being in JavaScript mode as a benefit (no invented scope to learn or inject things into, no invented logic to learn, everything is lintable, easy-to-follow state change flow) that's worth the drawbacks (un-pretty conditionals in render(), manually handling form input), but I can also echo the feedback in this article when it comes to having designers working on your components.
> JSX is also the reason when you have to keep splitting your 15-lines-of-html-code component to 3 components, 5-lines-of-code-in-each.
> ...this approach of splitting components into super-dumb components because of JSX restrictions will always put you out of flow when you are solving real business task
I don't understand what this has to do with JSX without an example.
> ...now you have to create 10 functions to get input from 10 inputs. 80% of these functions will contain single line with this.setState() call
Working with forms is definitely one of the most painful parts of React, and one of the differences I most enjoyed when porting our sample app to Vue.js 1.x for inputs which only affect the value they bind (most interesting thing I learnt: the React component structure the original was written with mapped almost verbatim to Vue.js components, the main difference was in flexiblity of what you can pass down the tree - e.g. React components as props, but I believe Vue.js 2.x is now closer to React's flexibility), but most of this section comes across as hyperbolic.
Writing onChange handlers which are as generic as you can get away with for the current form is key, but it generalises to setting state based on input names, which can as be simple as the name of the state variable, or a path in state which should be set for simple form input even in deeply-nested forms, plus the appropriate value based on the input type.
e.g. if you're doing a simple form with text inputs, selects, radios etc. where checkboxes always correspond to boolean state, you could use this for every field (you don't even have to put it on each input, you can let onChange bubble up to a form with onChange={this.handleChange}):
handleChange(e) {
let {name, type} = e.target
let valueProp = type === 'checkbox' ? 'checked' : 'value'
this.setState({[name]: e.target[valueProp]})
}
(It's game over for simplicity once you want to do proper, user-friendly form validation, but that's a truth universally acknowledged :))
"I expect Vue to become a primary JS framework in 16-24 months if Evan You makes right steps, at least around backenders and smaller teams of frontenders."
When Vue.js gets a big enough community passionate enough to host their own conference, we'll be able to consider this as a possibility. :)
React is just the UI piece of the puzzle. Here's a nice description of when to use Redux:
"[Redux is justified when] you have a piece of data that needs to be used in multiple places in your app, and passing it via props makes your components break the single-responsibility principle (i.e. makes their interface make less sense)" (https://github.com/petehunt/react-howto/issues/12#issuecomme...)
This comment was written for Flux, but it is completely applicable for Redux.
When building something non-trivial, there are other pieces you'll want to pull in with React such as routing, messaging, etc.
I once wanted to use React as a virtual DOM library, nothing more. Turned out that I had to create "components" for every div I wanted to draw. Of course, this was a nuisance to the point that I had to let go of React.
Interesting, I didn't know, although I can recall searching through the documentation for answers. Does calling the "render" function multiple times perform the DOM-diffing and updating?
And can I be sure that React will not perform updates behind the scenes at other moments than when calling "render"?
In answer to your second question, yes, React currently only does anything as a consequence of calling `render`, or `.setState()`/`.forceUpdate()` in the case of a component class (not relevant if you're not using component classes).
In future, the (currently experimental) 'fiber' render will allow some rendering to be deferred until after the current call stack has finished (to avoid blocking the UI), but there should be away to tell React to do all rendering synchronously if you desire (which is necessary for eg. rendering on the server). There's no reason why the current behavior couldn't be supported on top of the new experimental renderer though.
"JSX is also the reason when you have to keep splitting your 15-lines-of-html-code component to 3 components, 5-lines-of-code-in-each."
this stuck with me the most
Can't comment on vue much other than I think it would be the one I would go with if I had to pick one of these js frameworks due to some of the nice projects I've seen in little code. But yii2 for admin panels seems like another great selection for generating quick ugly forms only 5 people might see a month.
With all the evangelism I've seen on HN about React, I have yet to see a cohesive post about the benefits that it provides that makes it worth the investment in learning.
Nor have I seen a seen a good review of tooling that provides a good path for someone who wants to try it out.
What I do see, are arguments that "it can do that too if you only knew how to use it!" That and a lot of sample code that embeds html within the code, which frankly looks like a delegation nightmare. (and scattered postings about documentation not being up to date)
You could downvote me. Or... you could point me to a helpful and up to date resource or recent posting that is actually helpful. Or better yet, write one.
Clickbait title for the HN crowd, I sense that articles like these are analogous to the old which color to paint the bikeshed debate.
Front-end libraries and frameworks should be trivial because front-end web development is largely trivial, it's the ecosystem around it that has bloated in complexity, including Vue.js and React.
Take a standard API that is already simple enough to understand and use (DOM), and re-package it for people who wish to call themselves "software engineers" to justify the time they spend on making simple things work in a complicated fashion. If you disagree that front-end complexity is getting way out of hand, just read the source code of any modern single-page app including its dependencies.
I think that code written by amateurs cobbling together vanilla JS is generally faster in development and performance, more easily understood, and easier to maintain than code written by a professional web developer using whatever framework. The early web itself was largely cobbled together by hobbyists, and so should it continue to be.
The industry disagrees with me, that's fine. I'm aware there are many reasons why my views are the exception not the norm. I just hope that something far better supercedes this era of web development, which would require social and cultural shifts to occur.
"Not being able to put plain old IF condition to some block of HTML code sucks"
In my usage of React, I found that this limitation forces me to use functions to break down my code, a skill which is simply required when working on large projects. Of course, that's what everyone else says, too.
"JSX is also the reason when you have to keep splitting your 15-lines-of-html-code component to 3 components, 5-lines-of-code-in-each."
Truth to this -- React can make things slower when your project is inherently monolithic, but you're tempted to abstract things into ugly Listwrappers, ListViews, ListViewData, ListViewDataContainers, etc. It gets ugly if you aren't good at abstracting things very well.
React should approached with caution. I think this guy has the right idea, don't put all your eggs into the React basket. Don't underestimate the cunning of Mark Zuckerberg. If possible, don't rely on React, because if you create something groundbreaking, you will be in for a legal situation with Facebook.
1. This was mentioned already, but, yes, you can use ternaries and boolean logic for simple conditionals (loggedIn && <a>Logout</a> || <a>Login</a>)
2. When you need more markup, put them in an if-else statement in the same render function.
3. With SFC it's trivial to split these out into new components. You can even use bound methods to reuse the component state and props. 4. And finally, what stops you from creating a custom component that works like this? There's a continuum of ways you can structure your code, it just takes some experimentation to find what works for you.After working with Angular templates for a long time and then switching to JSX, I'm never going back to having my markup in a string blob with magical attributes that make it do stuff.