React JS as an Ecosystem,

and why we should save it from Facebook.

“Colourful Ensemble” by Wassily Kandinsky (1938)

React has definitely brought a challenge that has become a revolution about how we write UI code. But the patterns and practices that are followed by developers is not always in line with the core principles that were the reasons for React to be developed in its first place. When one understands those core principles, one can write React code with more confidence and state-of-the-art way, and thus more efficiently.

There’s a lot of good buzz about React out there: Loads of tutorials about how to learn it, how to write components, how to reuse existing components, how to connect to state containers, how to route, how to insert in DOM, how to use it with this and that etc. But there’s too few documentation about why and how React has deserved its popularity over others from the conceptual and technical point of view.

This will be a write-up with an intention to reveal those core principles that are seemingly too obscure otherwise.

First of all, I don’t want to “promote” you to use ReactJS necessarily. It’s good. But there’s others out there too, such as VueJS. I’d favor Vue over React, and the reason is not technical. You can read the interview with Evan You, the creator of VueJS, if you like to know more. I just happened to have learnt React and want to share my knowledge.

So let’s start with a very basic knowledge about how it’s all started: the standard technologies that have always enabled people to use internet in order to communicate to each other: HTML, CSS & Javascript and a browser to work these out: which works as medium to turn structured raw data into human-perceivable information.

Before React, and everything alike…

Following section could be really basic for most of you, but I recommend to stick to it anyways. It’s never bad to remember the basics to understand where an evolution is headed.

Front-end implementation of a web-based system is the part of an application that concerns everything delivered to user’s device (browser). In its most fundamental form, this consists of files separately provided and written in HTML, CSS and Javascript.

  • HTML: What a given UI consists of: the Content (text, images, videos, hyperlinks)
  • CSS: How a given UI looks: the Appearance (layout, size, color, typography etc.)
  • JS: How a given UI behaves: the Logic (forms, configurations, events, storage, handling server communications etc.)

Separation of Concerns

Before, these above parts were all separated in an application both during the development and in its procession in browser; in order to provide a sensible organization of a given code stack as a GUI (graphical user interface) to users. Basically during the development, we the developers had mimicked the way it will be organized with formats in the browser when it’s in its working form, and we fancied to term it as “Separation of Concerns”. Although it was just a mimicry of how browser separates the whole junk of code, some really advocated that we shall just do the development the same way as we deliver — developing JS, CSS and HTML separated from each other. Then this led us to inventing new tricks, such as templating languages, in order to bind their instances together.

Binding problem and two-way binding

This helped bring up some consistency. However it also brought up some complications. Because there was a problem with this approach: It required too much repetition of code for identical UI elements to be implemented, in order to work on tasks that required different logic.

There was another problem. If we had a content element (say <input />), that needed a certain behavior attached to it with Javascript (i.e. focus event), we had to give an id/class and use a templating language of some kind, to bind them together, usually in a completely different file located elsewhere. So the two things that were essentially supposed to work together had to be separated.

Because? Conventions.

This approach was useful in a sense; i.e. if you wanted to call the same function (e.g. event handler), by using different elements within the application. The founding principle of this was also re-usability indeed. However, the problem was direct usage of a generic UI element in relation to a certain and specific action, which meant that the UI had to be redesigned and developed if a similar but a little different action needed to be called.

Re-usability is not just about being easily able to reuse a node: template, component or a function for calling identical actions; it is also about maximizing the usage of any piece of code written in order to do similar actions that vary from each other too.

Whomever has worked with tons of such event handlers and helpers knows the pain of writing these bindings and trying to find them later to update.

Basically, it was too much to try to couple and bind stuff.

Finally some people came to a point to understand that Browser’s Concerns in how they interpret code didn’t have to be same as Developer’s Concerns.

Then the Web Components came into picture as a concept, although never really made it to widespread usage. However React provided an entirely new way of writing UI code — JSX-Components.

Whose ultimate principle was:

Re-usability

A reusable booster rocket called: “Of Course I Still Love You” (drone-ship of recent SpaceX Falcon 9) landing back to the earth after a boost-launch of SpaceX Falcon 9 without unpredicted results. Credit: SpaceX

Separate UI parts from each other, and from business logic, entirely.

This way, we could easily reuse a component that we have previously built, not only within the application we’re currently developing; but also across many different projects. Because React redefined the concerns that needed to be separated. The biggest challenge they brought was to be able to write HTML, CSS & JS all within one file (JSX), representing one component and thus delivering a fully fetched, a completely autonomous node; which could then serve a purpose in whichever context.

Abstraction-API

With React, you can build a component that can do either or any combination of what html, css and javascript does. It’s basically an abstraction-API to build with ease, for the web.

An era of fully autonomous nodes

So the new concern was the mission of each micro UI-element working in relation to any given context, rather than the technical language that a typical web-application is constructed of.

“If one can figure out how to effectively reuse rockets just like airplanes, the cost of access to space will be reduced by as much as a factor of a hundred. A fully reusable vehicle has never been done before. That really is the fundamental breakthrough needed to revolutionize access to space.” Elon Musk

SpaceX has a radical interest in reusable rockets, you can read more about it here: http://www.spacex.com/news/2013/03/31/reusability-key-making-human-life-multi-planetary

It’s finally been understood that it was machine’s concern to get a file in .x or .y format, but it was humans concern to make it work efficiently independent of business requirements, and reduce unnecessary repetition. Thus the new concerns were rather the effectiveness of each micro-UI element (button, input, search-form, form, table, and any such possible combination of such items; looking, behaving, persisting the same way regardless of any context), how to enable them to work with each other, and in relation to any given context by providing an api to make them work flawlessly.

Props & State: Abstract communication between components

Indeed many templating languages, such as Handlebars, have already tried to address re-usability concept and enabled developers to easily reuse UI elements in various places in their applications. However, the patterns for transferring data in between UI elements were not really addressed well and the ways to do so were not intuitive. The end product was not fully and easily reusable. One had to juggle too much.

But with React, it was as easy as passing a, what they called, “prop”, which was just like an html element attribute, to transfer data to a child component:

<ChildComponent prop=“prop value”/>

which, in the real world, could be:

// example of creating a stateless React component
const Button = (prop) => (
<button
onClick={prop.onClick}
style={{backgroundColor:
prop.type === 'call-to-action' ? 'green' : 'white'
}}
>
{props.children}
</button>
)
// example of rendering above component with React
<Button
type=“call-to-action” // this is a string prop
onClick={this.bringSignupModal} // this is a function prop
>
Signup
</Button >

A prop could be just about any data type: number, array, object, function, string, boolean. All it enabled was to create an abstraction as an API, to allow autonomy for each component, to allow them to be fully compatible to be used in different scenarios. But of course, a component had to have a predefined set of data types one could pass into each prop it had, for validation purposes.

With React dev-tools, it’s very easy to debug props and state during development

For a node to be fully autonomous, it has to have right skills to communicate well in different scenarios with different nodes. This sounds like just basic, pure natural law, but it could be complicated. Let’s see an example:

Missionary as metaphor

Imagine you have a new religion (say it’s “Pure Love”), and you have missionaries. You give them the book to deliver your message. They are not supposed to change the book, right? So this is where the props come into picture as immutable data sets:

A component (a missionary) cannot change a prop (the book) given to it.

So the missionaries, however, need to adjust to different cultures when they are spreading the love. Right. Maybe sell the book in some places, and gift them in others. So if they had to behave differently to any context, they had to switch to another “mode”. This is the state in React.

A component (a missionary) can render (behave), based on different states (cultures).

So in a React component, prop was provided from without, and state was handled from within. Prop was about component’s communication with different components for a given mission, and state was about component’s autonomy and extended integrity.

I don’t really know why I’m writing in past tense by the way. I guess for the sake of storytelling.

These provided developers to create components that they could not only reuse in different places within an app or apps; but also develop and serve them most efficiently and collaboratively: the open-source way.

Just Javascript

Another way that React made itself superior to many others was actually how native Javascript was used to propagate it. By using many standards both from ES5 and ES6; a developer learning React was actually learning Javascript and its new features. One didn’t have to learn this new other templating language and its idiosyncratic way to resolve the binding problem:

One only had to conceive a conceptual comprehension of a new philosophic system about how to write UI code, and why so.

At the end, all the components we write in React are pure functions and ES6 classes. Well of course there’s this new “JSX” syntax, and it actually takes a bit time to digest. Though this is true more for experienced programmers who are not used to it rather than inexperienced ones, indeed. The only thing is we were never used to mixing HTML with Javascript; probably just because of our taboos about the separation of concerns… And at times when we mixed up CSS with HTML, it was even worse that we tried to avoid it at all costs.

Every React component must return a node. image credit: Andrew Hull

Virtual DOM & Data Flow

To be frank with you, I never understood the technicality of Virtual DOM. But apparently, you can fake nodes in a browser. I mean all these HTML elements that we give to the browser that turns into nodes, can be faked up and worked around in the background, apparently. But then the fake ones can work the same; so it’s not fake..? FTW.

“The Virtual DOM is an abstraction of the HTML DOM. It is lightweight and detached from the browser-specific implementation details. Since the DOM itself was already an abstraction, the virtual DOM is, in fact, an abstraction of an abstraction.” (source)

Anyways, React really shines here. The performance part of React by utilizing this Virtual DOM technology was one of the few challenges it has brought. Otherwise, a concept such as “one-way binding” would not be as performative, if possible at all, because it requires every user input to be first propagated in a higher order state (your component, HOC, or a flux store); before it can be rendered simultaneously as user types. So not using virtual DOM, apparently, suffers in performance, especially for such scenarios where data flows quite a bit.

It’s important to note that Virtual DOM as a concept and technology existed prior to React, and has been used widely within other frameworks as well, such as VueJS, Mithril, Bobril etc. If you want to explore a native implementation, visit Matt Esch’s implementation.

Controlled & Uncontrolled components

As previously said, React’s performance power in its technical implementation relies on the concept of one-way binding. What does this mean? This means that when one types text on an input field, it actually works in a way as explained above — by first registering a user typed value in a local or global state; and then propagating it within the UI, in contrast to two-way binding as it is in many other MVC frameworks. Two-way binding works in a way to simultaneously register a given user-generated input to appear on the UI view (“V”), right away with a Controller (“C”) against the model (“M”).

But then, what if there’s incompatibilities between the authenticity of data flowing in two-ways thus multiplied? This is the main problem with two-way binding.

Single Source of Truth

This is a concept that allows us to prevent incompatibilities between two different ways of registering data (if designed well). There has been a lot of different solutions made to address this, but, in my opinion, this is still the weakest and strongest part of React. Weakest because React does absolutely nothing to resolve this. Strongest because it denies taking any responsibility at all. It only cares about the view layer. Facebook has introduced Flux as an architecture, but it is far from a typical, resolutive solution. Reflux, redux, and similar solutions still suffer the problem of repetitive boilerplate codes and a lack of intuition, in contrast to main principles of React.

Ironically, best and easiest way to resolve the state problem in React, in my very opinion, was introduced with a non-flux pattern, using observables, with Mobx.

Getting too used to using uncontrolled components may make you regret the complexities and incompatibilities that may appear in the future. Because there’ll be too much of local states segregated from each other. But sometimes it’s wiser to do so, because it’s more of a natural approach to provide a user with an input and then allow her to be free with it about what she types, until she commits the changes (e.g. click the submit button).

For that reason, for example, it’s always wise to use a Higher Order Component to validate a form before registering in a global state container.

Higher Order Components (HOC)

A HOC is a kind of component that takes in a component, and renders another component with some javascript wizardry; which in turn becomes a more intelligently designed ecosystem of components that feed one another.

A good approach I’ve adopted so far that keeps me consistent during development is:

If a provided field needs to populate or be processed somewhere in an application simultaneously, it’s better to use controlled components to share the same state. Otherwise, it’s best to keep the autonomy to user and allow them to type without registering beyond the scope of a given UI, either with uncontrolled components or components wrapped with a controlling HOC. A HOC can handle your validation, scope and update changes concurrently.

Getting too used to using uncontrolled components will create a lot of local states in an application though, which invites for incompatibilities in the data flow.

Though using HOC can also be too much, when it becomes a habit. For instance, Redux’s connect() is a good example for a possibility of over-usage. When you click React dev-tools and see the DOM tree like this, it doesn’t look so human-friendly with all components being called Connect, at least to me:

An Ecosystem beyond its underlying technology

Making a complex UI is not so easy. However, re-using an existing one is. This is thanks to many existing UI libraries built with React, which provide most of commonly used elements with their designs applied (that you can also change).

But there’s also these kinds of complex components that one sometimes needs, but no library has actually have provided it. Say, a date-range-picker, an image-resizer, an S3-file-uploader, a notification-handler, a form-validator, a canvas-drawer etc.

So we have built an ecosystem of resolving UI-building challenges, all together. We should be proud of it. This is arguably the best thing happened for a typical UI developer of React kind: https://react.parts

But this comes with a risk that involves power games.

Facebook as Incubator

Facebook helped create React. One may of course claim that Facebook created React, which is also partially true. It does matter indeed. React has become popular of course partially due to its well-designed architecture, support, incubation and implementation by Facebook, and of course just its name. But it’s also because of all the developers creating an immense amount of resources to collaborate with each other and serve to the world. Yes we’re thankful to Facebook for what they’ve initiated, but it has become something beyond what they invented.

As some of you may know, until recently, Facebook did not want to give away React to be freely used by all developers and companies. They had licensed it in a way to use React as a way to proclaim power over other companies using it, to prevent potential competitors to advance over them, using their baby.

It is not so uncommon in history that empires lose their power precisely due to the technology they have created themselves. This would never conclude that the technology were never supposed to be created, or it was not good for the empire to have created it. It’s only that there’s a necessary evolution need to be processed, and it had to be done by either of the strong ones.

We should already start creating ways to reclaim React against Facebook. It was great that it is now licensed with MIT license. However, this is not sufficient. We need to fork it and remake of it; copy, iterate, develop, minimize and transform; for better stuff to come out of it. So we don’t only have one empire, or a few, ruling the underlying technologies for social communications on internet.

Some actually already have done it. I love the people who have built, Preact and Nerv. Kudos! Is there more? Comment!

Once upon a time in future, it is inevitable that Facebook and React will both be obsolete. So let’s already imagine how React can be immutable by Facebook, and what will (and should) come next.

If you have any thing to say: comment, disagreement, addition, correction or just a thank; feel free to write comment. Thank you for having read