My Reaction to React
pseudoconcurrentthought.wordpress.com
pseudoconcurrentthought.wordpress.com
Perhaps the most valuable thing about frameworks is that they are common languages. They make it easier for developers to dive into a new code base and quickly understand what's going on. It's not entirely about functionality. I think this is partly why framework usage seems to be so trend and style driven; everyone wants to be using what everyone else is using.
given that software development is mainly about managing expectations this is of huge value
I like that. It's a nice way to put it.
If writing a framework is not a goal of the project, don't write your own framework. And few projects have the clear goal of writing a new framework (especially in addition to any other goals like creating a product).
If you are architecting a product meant to scale, choosing a framework with significant mindshare, great documentation, and tons of learning materials and blogs supporting it is the right way to go. Frameworks are also supported by other frameworks. React/Redux has popular tools for debugging, logging, asynchronous operations, server-side rendering. I'm sure there are similar angular ecosystem frameworks as well.
I once read an article [1] that argued Lisp did not reach the same level of industrial popularity as other programming languages due to the fact that Lisp enables you to program in a lot of different ways for different reasons. I'm admittedly not very familiar with Lisp, and I don't know if I fully agree with the article, but it made me wonder if ease-of-collaboration can be considered a useful perk for languages/frameworks.
By the time Django finally broke through, PHP (with a good-enough mini-framework baked in) already dominated Python for web development, and the fragmentation of the Python world was arguably a contributing factor. Others adopted a third language because of a single mindshare-heavy framework, Rails.
mod_python didnt come around until 2000. by then php4 was already out
You could make a fair argument that ease of collaboration is the useful perk for the kinds of framework we’re discussing here.
In most cases, these frameworks don’t offer radical new functionality, but they do provide a focal point for developers interested in similar functionality.
For comparison: I think React is (currently) still in the small category, I think Angular is waaay to big.
This way you'll have tutorials, courses, books, stackexchange, educated talent, new features and bug fixes -- it all comes your way if you pick a popular-enough library.
This is probably since the dependency injection, router, http, web worker, service worker, and testing modules will be properly split off at some point, as well as the polyfills. That leaves the necessary polyfills as zone.js (as of a couple of days ago a presented Stage 0 proposal), rx.js (the ES7 Observables proposal), reflect-metadata (ES7 decorator proposal), & an ES6 shim, and the necessary non-polyfill dependency of DI - all of these are pretty light.
Otherwise, I pretty much agree with the benefits of choosing a popular library/framework. The homebrewed HTML generation in the original article was quite painful to read, and if all someone is interested in is to figure out the HTML structure and how CSS interplays with it to style it appropriately, this pattern will fail fast. Angular, Ember, and React (or whatever popular/semi-popular library/framework) allow for much better template expression than this.
In addition, typing out all of that is tedious - repeating stuff like document.createElement every time will get old fast. One will then want to create a custom HTML rendering method that generates the appropriate DOM node depending on the string passed to the function. Then one will start trying to figure out optimizations since it turns out raw DOM generation/manipulation has surprising performance issues in some situations...at which point, one encounters what Angular 2, React, and virtual-dom have all encountered & largely solved. This doesn't even get into various other optimizations, such as using document.createDocumentFragment, creating a caching strategy, avoiding unnecessary node generation, etc., or writing the components such that they cannot be optimized by leveraging web workers.
It may be a fun academic exercise to create a rendering library, but in practice it is difficult to create a robust solution, especially one that works for a team. Doing a rough cost-benefit analysis, this path is seldom a fruitful use of one's time, unless one enjoys such forays & solving these problems.
Ruby and Python have Rails and Django which goes a LOOOOONG way in fixing this problem. Not many languages have that one, dominant framework and usually that's because people keep inventing new ones to deal with shortcomings of current ones OR that the frameworks do so little on top of what the language already offers that it's easy to create your own. Javascript and PHP are clear cut cases for the latter since both languages are out of the box built for the web. jQuery was the last real unification in the Javascript world.
I don't entirely care which framework becomes dominant as much as I just want A framework to become dominant. React looks like it is gaining that momentum, but you immediately see the problem play out when there's a thread about how great React is followed by 100 "X is better because it doesn't handle Y the way that React does" followed by another post about how "X is worse because of the way it handles Y". There's something about the Javascript world that seems ready to create new frameworks instead of contributing to existing ones.
I took a sales class years ago and the biggest takeaway from it was "People buy pain relief". jQuery was dominant because it solved a huge pain point, cross browser compatibility, in a way that made natural sense for people working in the browser by using CSS references...AND it was built to run side by side with any other JS library (Prototype, Mootools, etc) so you could safely invest in learning it and know you'd be able to use it on any project that came along. During a time when IE6 compatibility was a big deal this was huge. During a time when a lot of people were trying to solve the problem and you'd inevitably end up on a project that chose one of the other dozen options, side by side compatibility was huge.
These were major points of pain relief that jQuery brought to the table and that's how it won.
I'm really hoping that one of these React dialects will win out soon, as it's not really a "common language" until everything is mutually intelligible.
Much like jQuery being able to work with other JS libraries smoothly was a big selling point, React seems to be providing a modular approach that's flexible enough to work with many of the more opinionated options out there without having to dictate everything about the application.
One of the biggest churn points around JS frameworks wanting to do things this way or that way, full single page app or hybrid server side / client side, integrate to existing site or build from scratch.
End of the day, the browser is the view layer. Most of the other frameworks that try to make it significantly more than that are always going to lose when being applied to existing systems or server side heavy systems.
The React approach is basically just simplifying and removing pain points. It's easier for Rails to define some standards on the server and database side because the server side is where the core logic of every application lives. You're not going to try to apply Rails to an existing application, so it doesn't have to worry about fighting that battle. That is a major consideration of client side code, which is why you're seeing more wide spread usage of React. It fits more use cases instead of trying to be Rails in the browser.
A set of sane, accepted defaults would help the community tremendously. Personally, I'm hopeful that that's what React/Redux/Webpack turns out to be.
In Rails, there's a default view layer handled by ERB but it can be mixed and matched with HAML, Slim or any other view layer. Likewise, you can use ERB, HAML and Slim outside of Rails entirely.
There are frameworks like Meteor that let you have an interchangeable view layer. There are others that build the entire full stack framework around THEIR view layer.
If Meteor made React the default view layer...that would be a step towards unifying the fronts. One full stack system with a shared layer that can be use inside or outside of that particular framework.
Yeah, it would be good to get a router and couple that with React. React is not a total solution for making a web app, and anyone that picks it up seriously will learn that very quickly.
We need lots more libraries like React that focus on one area of development and do that well rather than all these own-the-world frameworks that have both shiny and awkward parts. I want devs to do their front-end library selections very carefully and build a mosaic that fits together well for their app's particular use cases.
When I was first looking at python frameworks, I had to spend a not insignificant amount of time evaluating the various frameworks before deciding which one to hitch my wagon to. Had I decided on Ruby over Python, the choice would have been easy given the clear dominance of Rails.
I have limited time to learn new tools since coding is not my primary focus, and one thing that is holding me back from learning a javascript framework is trying to decide which one to dedicate my time to. They all have pros and cons, and I hope a dominant framework emerges soon, and the bulk of the community rallies around it to make it better and better.
Obligatory: https://xkcd.com/927/
What I don't like is a when a library sneaks it's way into all of my code. The rest of my application shouldn't care what technology I am using for my views. I should be able to swap between the DOM API, jQuery, React, mustache, etc without having to write a single line of code outside of my views.
Hands down, the worst code I have ever inherited from another developer is in a scenario like this. Happened to me a bunch of times. Worst ever was a former boss who didnt "trust" Prototype.js nor jQuery and decided to write his own version. Pure hell.
Please be kind to your fellow programmer brethren. Unless the problem you are trying to solve is uber simple and obvious or you are just "doing it for fun/knowledge/etc", find a well-adopted framework, with good documentation and get to work.
But if you have different ideas about how to structure things, come up with new abstractions that you find solve the problems at hand better than any of the abstractions available to you, then by all means do roll your own. We don't need more clones, but we do need fresh thinking and ideas that don't follow the pack. That's how we progress, by challenging the status quo.
Apologies for the incoherent rant, I hope the point gets across anyway.
My view on this is that generally if you haven't extensively used at least a couple of existing frameworks, it seems unlikely you'll do anything than re-invent existing stuff (at best) in a slightly different fashion. But otherwise I definitely agree the "use whats out there" gets way out of hand -- but for me this is mostly for relatively straight forward stuff.
If your background is mainly in modern JS development, that’s probably true. I don’t think it holds more widely, though. Modern JS lives a little bit in its own world, and the state of the art in that world is sometimes decades behind the wider programming industry.
With the interest in things like React and Flux there has been a lot of discussion in the JS community recently about unidirectional data flow. However, the same sort of separation of input interactions from output rendering goes back to at least the 1970s and 1980s when ideas like MVC were being developed.
Similarly, React and similar libraries get a lot of attention for the declarative way you can specify rendering and the relatively efficient way they update the DOM, but again we’ve had declarative UI libraries on the desktop for decades, and anyone who was doing graphics programming in the last millennium will be all too familiar with doing batched updates.
It’s not much of a stretch to think that someone with a background building UIs in some of these other contexts might have different ideas to the current JS community about the architecture they want for their UI code, nor that some of those different ideas might be better for some projects than the mainstream today.
With the current lineup of frameworks, there's a lot of effort made to remove state from the system in order to make it understandable and performant (which is reminiscent of how people talked about Haskel a few years ago).
Yet with Smalltalk the entire language and tool base embraced the existence of state and gave you a lot of tooling to help make it manageable.
To me, the main problem with frameworks such as Backbone/Angular 1 is that state was bidirectional and that anyone could attach event listeners on anything so your webpage was a network of state flow with none of that being transactional, nor guaranteeing that the system would come into a consistent/valid state.
React is great with their unidirectional approach for rendering, but when a deeply embedded component makes a state change for itself it may logically have to effect the entire system. The current practice is to have top-down handling with Dispatchers/Stores (Flux), or pure reducers (Redux).
Another approach would be to compartmentalize each component so actions can automatically bubble upwards where they are handled by whomever in the VirtualDOM tree can take up the task. This would do away with global dispatch, and make it easier to mix and match components. I think this approach has merit.
"RHTML turing complete?"
I never did find out the answer to that, because I only lasted one month at the job. I'm sure it was a great learning exercise / psychotic breakdown for the original author.
If you only need 2% of what a major framework offers, you are probably better off writing your own code that does exactly what you need.
"...and in the future, we can use all these other parts of the framework" is the mental error. This is YAGNI in minor disguise!
a) Difficult to read and mantain. (Compare with the version below).
b) Inefficient in a real world scenario as it has to recreate the DOM every time the model changes.
c) Difficult to test as it requires a DOM API.
d) XSS issues (Text returned from the service is not escaped in the DOM!)
e) Non isomorphic (Unless we have a DOM API in the server capable of emiting plain HTML).
Nevertheless, I agree that using React for such a trivial project would be too much, but there are other alternative frameworks that would fit for this kind of task (e.g. riot.js, Cycle.js, [Insert here your favourite one]).
My React version:
const DATA = {
name: 'John Smith',
imgURL: 'http://lorempixel.com/100/100/',
hobbyList: ['coding', 'writing', 'skiing']
}
const App = ({ profileData }) => (
<div>
<Profile { ...profileData } />
<Hobbies { ...profileData } />
</div>
);
const Profile = ({ name, imgURL }) => (
<div>
<h3>{name}</h3>
<img src={imgURL} />
</div>
);
const Hobbies = ({ hobbyList }) => (
<div>
<h5>My hobbies:</h5>
<ul>
{ hobbyList.map( (hobby, idx) => (
<li key={ idx }>{ hobby }</li>
))}
</ul>
</div>
);
ReactDOM.render(<App profileData={DATA} />, document.getElementById('content'));Of course for bigger projects, it pays off to use an automatic build tool like webpack or gulp.
https://jsbin.com/keyuqohusa/edit?html,js,output
https://babeljs.io/repl/#?experimental=false&evaluate=true&l...
If you're using a module importer already then adding React to your stack is pretty easy. For example with JSPM:
$ jspm install --dev react react-dom $ npm install --save-dev babel-preset-react
Then add 'react' to your .babelrc preset.
In your ES6 javascript file you can now use react via:
import React from 'react';
----
That's it.
However, if you have none of that already set up... Then you'll naturally be persuaded that now is the time to get a 'modern' javascript environment setup and doing so can take time. It took me about 2 days of beating through RequireJS --> Webpack --> JSPM before I settled on the latter.
Figuring all that was difficult, but looking back on it was extremely useful to now have all my Javascript bundling done within JSPM rather than using some Django bundler, and downloading raw JS files from the internet without evening using Babel to help me write ES6/ES7.
http://jamesknelson.com/learn-raw-react-no-jsx-flux-es6-webp...
The only essentials you need are React itself and, because the example uses ES2015 and JSX code, Babel to transpile the script into more portable JS that will run in today’s browsers.
In practice you’d probably also be using Node/NPM to manage packages and a tool like Browserify or Webpack to resolve dependencies. I’ll use Browserify.
So, here is a complete working example. For the script, we’ll use undo76’s original code verbatim, and add imports of the React modules at the start of the file. Let’s call this index.src.js:
import React from "react";
import ReactDOM from "react-dom";
const DATA = {
name: 'John Smith',
imgURL: 'http://lorempixel.com/100/100/',
hobbyList: ['coding', 'writing', 'skiing']
}
const App = ({ profileData }) => (
<div>
<Profile { ...profileData } />
<Hobbies { ...profileData } />
</div>
);
const Profile = ({ name, imgURL }) => (
<div>
<h3>{name}</h3>
<img src={imgURL} />
</div>
);
const Hobbies = ({ hobbyList }) => (
<div>
<h5>My hobbies:</h5>
<ul>
{ hobbyList.map( (hobby, idx) => (
<li key={ idx }>{ hobby }</li>
))}
</ul>
</div>
);
ReactDOM.render(<App profileData={DATA} />, document.getElementById('content'));
As usual, we need an HTML file to load that script, though it doesn’t need to do much else except provide a <div> with an ID where we’ll put the content that React renders. Otherwise just use your preferred boilerplate. Let’s call this index.html: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>React test</title>
</head>
<body>
<div id="content"></div>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
Finally, we need the tools and React packages: npm init
npm install --save react react-dom
npm install --save-dev browserify babelify babel-preset-es2015 babel-preset-react
Now we can run Browserify to generate our output JS file (adjust the / to \ if you’re running on Windows): node_modules/.bin/browserify index.src.js -o index.js -t [ babelify --presets [ es2015 react ] ]
That will produce index.js, which is just the code from undo76 linked with React and then transpiled to a more portable level of JS that today’s browsers can cope with. (Incidentally, this is literally the first example on the Babelify documentation page, which gives you an idea of how routine it is once you’re familiar with these tools.)Now load index.html in your browser of choice and enjoy. :-)
Also, what's with that syntax color scheme?
On the other hand, just by knowing Javascript and the DOM, you can understand exactly what is happening in the OP's code.
But yes, to use a technology, you need to understand it.
Regarding the size, you are right, I wouldn't recommend to use React for such a tiny task.
That said, please don't use the word "trolling" to make what is essentially an ad-hominem attack against someone whose point you disagree with. The author probably spent at least an hour, if not multiple hours, thinking through a problem and presenting a solution as a blog post. Whatever you think of his argument, this is clearly not the work of the troll.
"He's trolling" has recently become the tech community's version of Salem's "She's a witch."
My biggest concern with the original post is the next sentence, "If you want to use React, fine, I am not trying to convince anyone not to. I just want to show that components in a JavaScript application are quite simple to do and do not require any framework at all to do so." (The author has updated the post to clarify that "I am a proponent of using libraries and frameworks." I think that this was missing in the original post, I think that it would have been nice to add at the end of the post "Crazy, isn't it? Don't do it! Don't reinvent the wheel and tada-tada-tada...)
Not sure about the intentions of the author, but I think that the original post makes a great case to support the use of these frameworks and not the opposite.
Nevertheless, using a framework like React protects you automatically from accidentally adding XSS vulnerabilities.
...Why?
This solves none of the problems React was designed to solve and only makes things more complicated by introducing new APIs only you know.
Yes, this approach with vanilla JS is great for small apps. What makes you think this app won't grow?
I hardly see how this is a reaction to React other than to say "I didn't really read into why people are using React or what it's trying to solve, but I'm pretty sure I can solve this problem with my own framework I just whipped up.
Sorry for the brash delivery.
React could also still be implemented as part of the author's view because they haven't covered any of the problems with large cascading data updates. So there's literally no argument against React in this post. It's basically just a post about how to implement a design pattern in a language, React doesn't even need to be mentioned. I might even call it click bait.
"If you want to use React, fine, I am not trying to convince anyone not to. I just want to show that components in a JavaScript application are quite simple to do and do not require any framework at all to do so."
There are a lot of less experienced web developers being steered towards react that can gain a lot by understanding what is being laid out here, whereas I think more advanced developers like yourself have so much assumed knowledge that its hard for you to see past what from your perspective are glaring differences/inadequacies in the approach he's taking in the article.
I disagree. He actually is making an argument against React but disguising it with a passive-aggressive writing style. That said, it doesn't mean his article is not helpful because like you said, it did help you.
I interpreted the following paragraph as passive-aggressive:
"If you want to use React, fine, I am not trying to convince anyone not to. I just want to show that components in a JavaScript application are quite simple to do and do not require any framework at all to do so."
It follows the very familiar template of X-is-overkill-so-let-me-enlighten-you-young-grasshopper. Another example would be, "Hey, if you want to use a bazooka to kill a house fly, don't let me stop you but I just want to point out you can take a plain old rolled up newspaper and just swat at with a quick motion of the arm."
That type of rhetorical construct has been common sport in technical discussions for decades.[1]
Why interpret his paragraph like that? Look at his previous 2 paragraphs about seeing another "react, angular, ember", etc and how it's just tiring. (In other words, he's telegraphing to readers that he's intelligent enough not to have to learn them or need them.)
Yes, he does show the underlying skeleton of a "view" by showing some homegrown Javascript code but notice how he leaves out the concept of "DOM diffing algorithm". The virtual DOM is one of the features that makes React perform better with many components and changes.
Now if the author starts implementing more and more things that React does to achieve feature parity, he will end up inventing his own Pseudoconcurrentthought-framework. At that point, someone else will come along and write "the Pseudoconcurrentthought framework is not necessary. You can do it with plain old Javascript" At the point, the cycle of critique will have repeated itself.
[1]E.g. "Angular is overkill when you can just use JQuery"; "JQuery is overkill when you can just use plain Javascript getelementbyid()"; "Using Javascript on the web page form is overkill to compute sales tax since you can just issue a POST and have the server send back another HTML page with the new sales tax amount", and so on and so on.
The intended reader, as I interpreted it, would be the someone that reads Javascript Fatigue articles and goes "hell yeah". For this person the abundance of frameworks probably does feel tiresome. The person for whom this kind of advice would be patronizing doesn't seem to be who this article was meant for (although now I see what you mean by the title being click-bait)
a) building web front-ends by dividing them into components which are first-class citizens of the codebase, and can be composed, parameterized and reused, just like pure functions. [1]
b) expressing the view as a pure function of state has replaced any need to mutate the DOM manually and think about transitions ($.remove(), $.append() etc.). We need virtual-dom and diffing to be able to pull this off successfully, which makes this abstraction irreducible.
c) interspersing content-inside-code (JSX) is better than code-inside-content (template languages like Angular). [2]
The recent 'React fatigue' is due to people trying to figure out how to best manage state within this framework and causing a lot of noise in the process. And that is perfectly fine, but if you are confused by it, just use vanilla React and React's immutability helpers, keep all the state in the root node and pass everything down as props {...this.props}, and then when you get a hang of it, hop on to Redux. There is no 'one true way'; as long as your app works and you can hold it in your head, everything is fine.
[1] - http://www.jasimabasheer.com/posts/on-react.html [2] - http://www.jasimabasheer.com/posts/evolution-of-view-templat...
There is no 'one true way';
as long as your app works and
you can hold it in your
head, everything is fine.
With all due respect, this is the major criticism of adopting React, given that it's still in active development and given that many who are looking at using it have established apps using other patterns already.You can use React's immutability helpers inside it, or or performance in large state trees, use ImmutableJS that gives persistent immutable data-structures. This comes at the cost of having to use its own methods like map and filter, instead of normal JS everywhere.
But that is pretty much it. There are a few more other concerns that'll necessitate the use of redux-thunk, (which at its core is a few lines long), but you don't need to worry about any of this upfront. The thing with React is that unless you make costly architectural decisions upfront, you can always learn as you build, and figure out the right way to structure your project. Once you've built a fairly large project, you'll form your own set of opinions on which way you like to think about front-end code, and that'll inform you on your next project.
There is a learning curve, but with React, you are always thinking about fundamental things like encapsulation and message-passing than trying to learn non-transferable knowledge about a particular framework's quirks and conventions.
[1]: http://cycle.js.org
The Elm language is yet another area that gives the fear of missing out on the 'better than yesterday's abstraction'. But as long as I'm able to build great software with the tools I know and patterns my brain is comfortable manipulating, they can wait. This is the line of thinking that I mentioned in the original post about no one true way.
function Comp(state) {
return React.createElement(
'div', // tag name
{}, // props/attributes
'Hello ', state.name // children
);
}
And this is how you use it: ReactDOM.render(
React.createElement(Comp, {name: 'World'}),
document.getElementById('stage')
);
So in those situations the entire surface of the React API consists of two functions: React.createElement and ReactDOM.render. And if you use JSX, you won't even directly use React.createElement in your code.React is conceptually trivial. The API has been getting tighter with each release. React is in active development but so are all of its competitors[1][2]. React is production ready -- Facebook is even dogfooding the pre-releases in production.
[1]: in fact, when a library/frameworks stops being actively developed people start assuming it's dead. Counter-example: Redux is no longer actively being developed because it is officially complete and the implementation is so straightforward and resilient it can't really be improved right now.
[2]: the reason it's bogus to compare it to Angular2 "because that's not finished yet either" is that Angular2 is being built to spec whereas React is being developed under use. Angular2 will be "finished" when the full spec is implemented. React will be "finished" when real-world use shows no further need to change -- by that definition none of the alternatives (including Angular2 post-"final") is "finished" either.
Unless you write a blog post entitled "My reaction to react" and proceed to demonstrate components in straight javascript and that blog post winds up on HN where you're summarily dismissed as "doing it wrong."
var App = {
main: (function() {
window.addEventListener('load', function() {
// ... initialization ...
});
})()
};
The initialization code is with an event handler function, fine. But then:- Then registering of that event handler is stuffed into a closure, although it doesn't declare any variables or pollutes the global namespace in any way.
- This closure is then called immediately and its return value is stored into App.main, although it doesn't return anything, so App.main is declared as "undefined".
So there are two layers around that code which serve no purpose at all. Why not simplifying it? All you want is an App namespace and an event handler for window / load:
var App = {};
window.addEventListener('load', function() {
// ... initialization ...
});
Or, if you want a "real" main function (i.e. an "App.main" that is actually a function): var App = {
main: function() {
// ... initialization ...
}
};
window.addEventListener('load', App.main)
If you put your <script> tags within <body>, right before </body>, you could simplify this further to: var App = {
main: function() {
// ... initialization ...
}
};
App.main();The best thing about Polymer is that, unlike React, it works with W3C standards instead of going off on a tangent and hacking the DOM entirely. It extends current HTML5 standards instead of creating its own universe.
With Polymer, each component has its own mini-DOM which is actually a real DOM - Not the virtual layer you get in React which keeps overwriting the real DOM.
Unlike Angular, Polymer gives you a lot of control when it comes to how data flows throughout your app. Because of this, there are a few different component-level configs that you need get your head around. For example, by default in Polymer, data only flows downwards to child components, you have to enable a special 'notify' attribute to allow data to flow upwards to parents (this is different from Angular where data flows freely wherever there is a placeholder for it in your DOM).
I think React has been getting way too much hype. Polymer, on the other hand, is ridiculously under-hyped. Of those people I know who used both React and Polymer, all of them preferred Polymer. I'd like to hear alternative opinions from other people though.
While this sounds good on the surface (standards!) I think it is missing part the bigger picture. React, and more generally, the whole ecosystem of related libraries/frameworks it has spawned, is most importantly defined by a move to describing components using pure functions. The virtual DOM diffing is, in my view, just an implementation detail; a means towards achieving the end goal of a simpler program design via pure functions.
On a different but closely related note: Angular and Polymer both use template systems which have to reinvent control structures (looping, filtering, conditionals, ...) embedded into HTML via tag attributes (eg, `<li repeat="{{todoItems}}">`). Contrast this with React (and especially ClojureScript's Om or Reagent), where any such logic is implemented directly using the languages normal mechanisms for it (map/filter, loops and if statements, etc.). Using HTML template languages is realy just raising up HTML and treating it as some special class of data, whereas React-style libraries recognize that it's all just trees (AKA lists of lists), and programming languages are already very good at building them up and manipulating them. Programming languages are designed for manipulating data; HTML isn't.
"Note: The programming models of the two component systems (web components vs. react components) differ in that web components often expose an imperative API (for instance, a video web component might expose play() and pause() functions). To the extent that web components are declarative functions of their attributes, they should work, but to access the imperative APIs of a web component, you will need to attach a ref to the component and interact with the DOM node directly. If you are using third-party web components, the recommended solution is to write a React component that behaves as a wrapper for your web component. At this time, events emitted by a web component may not properly propagate through a React render tree. You will need to manually attach event handlers to handle these events within your React components."
It's worse than that, though. Web components that maintain their own state can be randomly squashed by React's virtual-DOM diffing algorithm because of the way elements are held in memory. They are just not compatible, and the React Core team has made no apologies about not agreeing with the overall concept of Web Components.
Multiple fields might belong to the same 'object' but each field is atomic and can be updated independently of the whole object (without having to diff the entire object each time). This is much more efficient on both the client and server because diffing is expensive and incurs a high latency and bandwidth overhead when you scale out. Diffing is useful for collaborative editing of unstructured text documents, but it is not needed for structured (or even semi-structured) data.
Looping and conditionals are often included in template languages because those are the most often used and most declarative control structures. More complex manipulations are left to code. This tends to work out very well in practice.
Until you want to automatically unregister event handlers when the component is removed
Until you want to compose them and select child and parent components without traversing the DOM
Until you want to pass options to the components in various ways, and have default values for them
Until you want to store component state and re-render part of the component whenever something in the state changes (since storing state in the DOM and reading it from there is bad)
Until you want to load javascript files on demand to construct and manage components instead of loading everything in one huge js file up front for a big website
Until you want to have a unified CSS convention so you can style all these components
That's when you need a well tested framework.
Because unless I'm very much mistaken:
ComponentWillUnmount Props Props state
for the first few complaints.
React is just the view layer, arguing against react because "you need a framework" is like arguing that no one should write their own applications without a framework. It is a separate discussion than what to use for the view rendering.
But React is about the view. You can't possibly be convinced that manually traversing the dom is just as easy and expressive as using JSX. Even in the simplest of interactive (as in you need Javascript) components or pages.
React's concept and syntax is super easy to understand and perfect for modularizing the components of your app. The real problem IMHO is the tool chain. That's what drives developers unfamiliar with the ecosystem away. And of course the fact that it seems to change all the time. The first time I looked at React they rolled their own transpiler. Now Babel is the recommended way to go.
According to the tutorial page you should either use browserify or webpack. You don't have to - but without them stuff gets messy pretty quick. Of course if you pick one of these up you also have to learn how to use them and you will want plugin A, B and C to get to your simple Hello, World React App in the first place.
So yeah. That's why it's so easy to step away from that thinking why don't I just simply roll my own framework.
Which is the same as saying "you have to".
Can't we just accept that developing with React is no longer as simple as just stitching some views together? It's as if the collective React community is very insecure about the fact that writing web applications is gonna be hard and complicated no matter how shiny your tools are.
Sure, you don't have to use JSX, but without it stuff gets messy pretty quick.
And you don't have to use flux/redux, but without it stuff gets messy pretty quick.
Also, you don't have to use ReactRouter, but without it stuff gets messy pretty quick.
You don't have to use....
I've been looking into using React (well for the past 4 days of solid research), but I'm finding that pure reducers are a mental-mismatch for me.
I'd like something that helps me manage state, and perhaps constraints its flow (like Reach does with unidirecitonal renddering), but not something that tries to abstract state away completely.
Frameworks don't exist just because someone wanted to write a framework. They exist because they solve problems. And they solve problems you likely forgot to think about so you don't have to. Like not losing cursor positions when re-rendering, or not breaking the DOM when trying to re-use input elements or manipulate tables.
React is actually great in this regard: it doesn't try to solve everything, it just focusses on one problem (two if you include React-DOM/Native) and solves it well. Redux is another great example (the entire API can be implemented in less than 100 lines).
The reason libraries and frameworks like React and Backbone and Angular and Ember exist is that direct DOM manipulation doesn't scale. It's on a lower level of abstraction than the application you're trying to build. And the advantage of React (and similar libraries like Mercury) is that it just lets you build components (i.e. partial DOM trees) -- it's trivial to swap the component library out in the future without having to touch any of the application logic around it.
I like the premise of the post, but I did not find the end result very convincing.
I very much enjoyed reading this one. Though I always find it more beginner friendly to start off with a framework rather than going vanilla. That goes for almost all subjects in tech. Then you can dive deeper into the material once you have a basic understanding.
Here is a link to the original article: https://medium.com/learning-new-stuff/building-your-first-re...
And look at those code examples in the article. Such a simple app, and yet already a confusing mass of IIFEs, module patterns and whatnot.
Framework churn is indeed tiring but throwing out what I would consider basic/essential tools of frontend (module bundling for starters) doesn't make sense.
Besides, React is a library for efficiently rendering large DOM trees ... so I'm not sure what point he's making by re-implementing an MVC framework?!
More specifically, he's manually adding and keeping track of all DOM elements. Once elements need to be updated, he would need to go back in the DOM and manually add/remove/change elements.. welcome back to the jquery messy world. Whereas with React, the render function doesn't change because it gets smartly rerendered.
Also, as far as I'm concerned, jsx is a big part of what I like about React. Basically, being able to add html from javascript instead of using all kind of hacks.
Optimized in the sense that it uses less memory and cpu. But the code isn't optimized for humans to reason about (not to mention changing it.)
React was never about performance, it's about maintainability, readability and reasonability.
For me readable and maintainable code is (almost always) more important than fast code.
I had a project with Angular where one page was really slow. I re-implemented it with backbone / jquery, it was a bit faster but really hard to read and maintain. With React, the code was simpler AND faster, which I was really surprised about.
The actual problem is how to efficiently traverse/modify DOM structure, in the end you'll just reimplement virtual dom.
As many have already stated, a tutorial like this is interesting for hobby projects, but I would not adopt this approach in production. Libraries and frameworks have a lot of energy invested in them and should be considered early.
I'm an iOS/Backend developer looking to do some lightweight front-end programming, and whenever I look at the JS landscape I shudder.
Nearly every suggestion from JS developers is on the line "Have you tried "React/Angular/Ember/ObscureJS?". The Grunt/Gulp/Yeoman/Bower/Npm/Batman.js etc toolchain makes me question my sanity. Is it so difficult to just use Plain Old JavaScript™ and be done with it?
Sorry for the rant, I wish novice JS developers like us had a better way to get initiated in the JS land.
Pick one. Yes, you will pick the wrong one. That's okay. It will always turn out to be the wrong one eventually (if only because your requirements will change).
Don't obsess with what's hot. Figure out why it's hot, and what makes it different than the thing that was hot the previous week. If there's no sufficiently discernible difference you can probably afford not to pay attention to it until it pops up again.
The frontend ecosystem is in constant flux because the frontend platform is in constant flux. HTML has stopped using version numbers. JS itself has transitioned to yearly releases. CSS has fragmented into dozens of separately versioned specs.
That's just the way it is.
[1] This is the important point. At the end of the day, no one cares what framework you use—whether your app works or not is what matters.
Homerolled solutions such as this are free of another developers assumptions, but tend to scale poorly. Generally they need to be modified as new requirements are created, or unforeseen circumstances arise.
Over time you end up putting together more and more logic in and the illogical conclusion is that you end up building your own heavily bespoke version of React/Angular/jQuery/whatever, before realising you actually need to go back and start again.
There is absolutely nothing wrong with writing your own libs (it's educational and character building!) but to chuck json through a constructor is trivial. Sure - this code renders views in a simple and relatively inefficient way, but drawing boxes is only part of what React is doing.
I really hoped that we learned something from the jQuery experience but it seems to happen again and, maybe this is just my feeling, but JavaScript is kind of the only big enough language with this issue.
> True; us, the Web community (which also built the frameworks) as a whole, is to blame.
Doesn't this come across a bit naive?
Is the suggestion that web development is somehow different than all other software development? or that unless you're one of the ~0 people who are able to build a usable programming language, OS, and libraries on top of them, that you're not a "decent developer"? Because while I get you're discussing JavaScript frameworks. "Learning the Framework" and not the details, has been the only reason software development has been able to scale so beautifully. Frameworks that lower the relative complexity should and are encouraged in all other forms of software development, why should web development be different?
React looks fine to me and at my daily job our frontend devs do some amazing job. I just wanted to learn and all I seem to find is how to learn javascript through React, and not React through Javascript.
I do agree this is a home made solution and would not work nicely with lots of devs involved. I'm talking about learning though, and we devs are usually bad teachers when we don't know how to boil it down to the essentials.
How many people do you know that only use React to draw boxes and not for the advantages it brings?
jQuery, sure, that's probably harmful in the long run, but you have to know JavaScript to use React.
/Structuring/ an app is a different skill that takes lots of consideration, especially in a language as flexible as JavaScript.
Yes, frameworks are built from the basics and novels are built from an alphabet.
However, Frameworks reduce relative complexity, increasing their audience. Novels actually have an increased relative complexity reducing their audience.
While, its hard to find good analogies outside software development, it might be more correct to say: if javascript is the alphabet, then React is a picture book.
Picture books lowering the relative complexity, allow literate and illiterate people alike to mostly understand a story. Here its easier to see that the Framework (pictures) help novices (the illiterate, i.e. children), as soon as possible, to become independent and productive (understand the story). There is also the added benefit that exposure to both words and pictures simultaneously allows for an understanding of the alphabet and grammar, i.e. helps the learning process.
If you're gonna be building a sophisticated application, it's going to have to deal with a TON of challenges, and there's not really any way around em. Why not learn some of the more robust tooling and make life easier for yourself?
1. Language forces you to model-view-controller style
2. Language makes the model immutable
3. Language forces you to use correct types which saves a lot of trouble.
On the other hand, I a new to frontend - so I might be wrong.
So I recommend the author learn minimalistic libraries like Riot instead of React. Those are really lightweight and very easy to grasp. However, even the docs of Riot could still be improved. Despite its simplicity, I could have learned it in half the time if it had a better tutorial.
Essentially, this means applying findings from UI design to framework API design. Here, the user is a developer, but surprisingly many principles still hold: Principle of least surprise, make similar things look similar, make different things clearly different, and so on.
Of course, I am missing many good features of React (due to my lack of understanding, as I am not a front end developer), but at least conceptually one could argue the original idea was there all along. Perhaps the real power of React lies in the excellent diff algorithm they came up with. Any thoughts?
But the more poignant observation about React is that the components aren't actually anything like templates. You can think of React components as descriptions of the structure of the DOM -- if the equivalent structures in the DOM already exist[1], they are just "progressively enhanced" when you run React on them. The only reason you would want to generate that HTML on the server with React instead of writing that HTML yourself is that it avoids unnecessary duplication.
[1]: currently React needs to add proprietary attributes to identify markup generated by React but this will be made redundant in an upcoming version.
So, be careful, avoid magic, let your software express requirements, and then choose a tool accordingly.
Do you think the camera from an iPhone is better than DSLR with a 5k lens?
For the kind of pictures I take the iPhone is more than enough, I don't want the bulk and all the options of a DSLR.
For the web apps I built, it would be a very big hassle todo then without React and the modern front-end stack.
To deal with the complexity of my projects I need hight end tools. A lot of people don't.
Why not create components that do still separate logic and view like Apache Wicket does/did?
I've ended up doing the same - writing yet another super minimal framework: https://github.com/techlayer/espresso.js
It borrows lots of concepts from React, but is faster & more memory efficient in under 500 LOCs.
For years, if you did a lot of work in JS, you were constantly being told to switch to a "real" language, that you "shouldn't reinvent the wheel", that you weren't a "real" developer. I think, for a lot of people who got into programming web sites through non-CS paths, that perception that JS wasn't "really programming" was helpful at first, to make it seem more accessible, but it is now hurting people. I've been working in JS (and other languages) for 20 years now. I've heard it all. First, JS wasn't C. Then, it wasn't Java. Then, it wasn't C#, or PHP. It was "too high level". It "couldn't perform". Nowadays, people want to call it "too low level", whatever that means. I don't think it's a great language, no, but the web as a platform has a lot of advantages that are extremely attractive to small teams (which I think are the vast majority of teams).
Beginners don't understand what is going on with their code. It's a mystery why it works at all. If you can trust yourself to build anything, then it doesn't really matter what framework you choose, or really if you even choose a framework. You know you can never truly get stuck in a corner, because you can always write another program to get yourself out of it in some way. But beginners--and not-quite-beginners in JS who have been indoctrinated into thinking they are perpetual beginners--lack that confidence.
Because of this, such people are fearful of striking their own path. They want to swim with the school--safety in numbers. But there isn't any one school, so when multiple frameworks are out, and you never know which your Snr. Dev is going to choose at your next job (and you're constantly fearful that your lack of skill will be recognized and you'll be booted), you start to worry about ever being able to keep up.
And it might seem like a paradox--why would any such people start a new framework project when they lack basic confidence in their own skills?--but I think this is why there are so many frameworks that have risen to the level of awareness in the popular conscience. There are a few people who have crossed the line into confidence, but they don't yet know that their surface syntax doesn't really make them any different than the others, and then the mass of unconfident people amplify the importance of the project beyond what it maybe should deserve, because of the worry that they might be missing out on some important information that will come up on a job interview in the near future. It used to be you didn't need to have intimate knowledge of your future employer's framework before you walked in the door, they just expected that you had applicable experience and would be able to learn it as you went.
If you're starting a project now, you don't need a JS framework. I see a lot of people thinking way too far ahead. For the vast majority of projects, they aren't Facebook. You don't need a framework to make a simple activity feed. I see very small code bases worried about continuous integration and automated build servers. Nobody can just play with code anymore. Everyone is thinking about "scalability" and "hiring" and "doing a startup". That's ostensibly why we are here on HN, but HN--contrary to popular belief--is not the be-all, end-all of the internet. I think this is also a contributing factor to tool fatigue. People are so afraid of "reinventing the wheel" that they aren't willing to just play around with code. They can't tolerate it for themselves and they can't tolerate it in others (because they fear it will become yet another thing they think they will have to learn). But playing and making your own framework is how you learn to evaluate the plethora of frameworks and throw away 90% of them for being trivially easy to implement on your own.
So what is the solution? A lot of people are doubling-down on the "don't reinvent the wheel" trope. I think that's stupidly close-minded and will lead to such people getting left behind in the coming Singularity. Even if the literal "singularity" never happens, the pace of technological development is not going to slow down just because you're uncomfortable with it. The only surviving strategy is to learn how to cope with the rapid change of the market. And you do that by learning the core concepts to the point that you are completely capable of "reinventing the wheel" whenever you damn well please.