React's philosophy of design-the beauty of simplicity

Source: Internet
Author: User

React originally came from a Facebook-based advertising system project, where front-end development was a huge challenge in the implementation of the project, and the code became bloated and messy and difficult to maintain. So, they decided to throw away many so-called "best practices" and rethink the way the front-end interface was built, so there was react.

React brings a lot of pioneering ideas to build the front-end interface, although one of the most important reasons to choose react is performance, but the design ideas behind the technology are worth thinking about. I also wrote an introductory article on react, and provided sample code that you can combine with reference.

Last month react released the latest version 0.13 and provided support for ES6. In the new version, a small change is that react cancels the automatic binding of the function, that is to say, it was possible to bind an event like this before:

<button onclick={this.handlesubmit}>submit</button>

In components defined in ES6 syntax, it must be written as:

<button Onclick={this.handlesubmit.bind (This)}>submit</button>

Learn about front-end development and JavaScript all know that when doing event binding we need to implement a closure through bind (or similar function) to let the event handler bring contextual information, which is determined by the JavaScript language feature. Prior to the 0.13 release, react automatically did this binding for each method of the component at initialization time, similar to the one that this.func = this.func.bind(this) can be written directly in the Jsx event bindings onClick={this.handleSubmit} .

On the surface, auto-binding is handy for development, but Facebook thinks it undermines JavaScript's language habits, and the magic logic behind it might confuse beginners, and even developers may be at a loss if they move from react to other libraries. For the same reason, react also cancels support for Mixin, ES6-based react components are no longer capable of code reuse or expansion in the form of mixin. Despite the inconvenience, Facebook believes that mixin adds to the unpredictable nature of the code and is not intuitive to understand. You can also refer to this article for thoughts on mixin.

Programming in a simple, intuitive, customary (idiomatic) way makes code easier to understand and easier to maintain and evolve. This is react's philosophy of design.

Write predictable, custom-compliant code

The so-called predictable (predictable) code is easy to understand. At the beginning of the react Developers Conference, react project manager Tom Occhino further elaborated the original intention of react birth, mentioned in the speech, react the greatest value is what? Is it a high-performance virtual DOM, server-side render, encapsulated event mechanism, or a complete error message? Although every point is important enough. But he points out that the most valuable thing about react is the declarative, intuitive way of programming.

Software engineering has never advocated the use of inscrutable techniques to program, instead, how to write understandable maintainable code is the key to quality and efficiency. Imagine, after one months, you look back at the code you write, whether or not you understand a variable, the meaning of an if judgment; a new colleague wants to add a little new feature or fix a bug, does he have enough confidence in his code not to introduce any side effects? As functionality increases, the code can easily become more complex, and these problems will become more and more serious, resulting in a hard-to-maintain code. And react claims that new colleagues can start developing new features even on the first day of joining.

So how did react do it?

Using JSX to visually define the user interface

JSX is the core component of react, which uses XML tags to directly declare the interface, and interface components can be nested between each other. But Jsx's first impression was rather "ugly." When the following example is first shown, even a lot of people call it "great retrogression (Huge Step backwards)":

var React = require (' React '); var message =  <div class= "Hello" onclick={somefunc}>    <span>hello World</span>  </div>; React.rendercomponent (message, document.body);

Embedding HTML directly into JavaScript code seems like a crazy thing to do. The "best practices" that people have spent years summing up the interface and business logic are completely broken. So why should react be such an alternative?

The original intention of the template is to allow non-developers to make certain changes to the interface. However, this intention is completely inapplicable in the current Web application, and the code logic behind each template relies heavily on the content in the template and the DOM structure, which are tightly coupled. Even if the separation of the file location, the two are actually one, and for the collaboration between the two have to introduce a lot of mechanisms and concepts. Take Angularjs's homepage sample code as an example:

<ul class= "unstyled" >  <li ng-repeat= "Todo in Todolist.todos" >    <input type= "checkbox" Ng-model = "Todo.done" >    <span class= "Done-{{todo.done}}" >{{todo.text}}</span>  </li></ul >

Although it's easy to understand the meaning of this little template, you can't start writing this code because you need to learn the whole set of syntax. For example, you need to know the exact meaning of a tag such as Ng-repeat, where "Todo in Todolist.todos" appears to be part of the repeat syntax, and perhaps other grammars exist; You can see a data binding such as {{Todo.text}}. So what do you do if you want to format the text (plus a formatter), and what kind of data structure is needed behind Ng-model?

Now let's see how react writes this logic:

... render:function () {  var lis = this.todoList.todos.map (function (TODO) {    return  (      <li>        <input type= "checkbox" checked={todo.done}>        <span classname= "Done-{todo.done}" >{todo.text} </span>      </li>);  });  Return (    <ul class= "unstyled" >      {lis}    </ul>  );} //...

As you can see, in addition to the alternative HTML tags, JSX does not introduce any new concepts (in fact HTML tags can be written entirely in JavaScript). The repeat in angular is replaced here by a simple array method map. Here you can use the familiar JavaScript syntax to define the interface, in the course of your thinking there is no need to have a template concept, you need to consider just how to build the entire interface with code. This natural and intuitive way directly reduces the react's learning threshold and makes the code easier to understand.

Simplified component model: the so-called component is actually the state machine

A component is not a new concept, it means the encapsulation of a standalone function or interface, to reuse, or to separate the business logic. React, however, understands the interface components:

The so-called component is the state machine

React the user interface as a simple state machine. When the component is in a state, the interface corresponding to that state is output. In this way, it is easy to ensure the consistency of the interface.

In react, you simply update the state of a component and then output the entire interface based on the new state. React is responsible for the most efficient way to compare two interfaces and update the DOM tree.

This component model simplifies the way we think: the management of components is the management of the state. Unlike other framework models, react components rarely need to expose component methods and external interactions. For example, a component has a read-only and edit two states. The general idea may be beginEditing() to provide and endEditing() such a way to achieve switching, while in react, what needs to be done is setState({editing: true/false}) . is responsible for correctly presenting the current state in the output logic of the component. In this way, you don't have to think about how the UI should be updated in beginediting and endediting, but just consider what the UI is like in a certain state. Obviously the latter is more natural and intuitive.

A component is the basic unit of building a user interface in react. They interact with the outside world in addition to the State, and there is the attribute (props). In fact, the state is more of a component's internal maintenance, and the property is passed in by the outside when the component is initialized (typically the data that the component needs to manage). React that the attribute should be read-only and should not change once the assignment has passed. The use of States and attributes is further explored in subsequent articles.

Every time the interface changes is a whole refresh

The two-tier programming model of the data model-driven UI interface looks intuitive from a conceptual point of view and is difficult to develop in practice. A change in the data model can lead to a simultaneous change in the UI scattered across multiple corners of the interface. The more complex the interface, the more difficult it is to maintain the consistency of the data and interface. Inside Facebook They call it "cascading updates," or cascading updates, meaning there is a dependency relationship between the UI interface. In order to maintain this dependency update, developers sometimes have to trigger a wide range of interface refreshes, many of which are not really needed. One of react's original intentions is that since the overall refresh is sure to solve the problem of cascading updates, why don't we just do it every time? Let the framework itself solve the problem of which local UI needs to be updated. This may sound challenging, but react has done so by virtual DOM.

About the principle of virtual Dom I had a more detailed introduction to the article at the end of last year, and I will not repeat it here. In short, the UI interface is a DOM tree, corresponding to the creation of a globally unique data model, each time the data model has any changes, the entire data model is applied to the UI Dom tree, by react to update the interface parts that need to be updated. It turns out that this approach simplifies the development logic and greatly improves performance.

With this in mind, when we consider the changing UI interface, we just need to consider the composition of the UI as a whole. The simplification of the programming model brings about the simplicity and ease of understanding of the code, which is the predictable (predictable) code that react constantly mentions, and the function of the code is easy to understand at a glance. Tom Occhino also shared a case of react's internal Facebook application at the React developer conference, and as new features were added to the system, the progress of the development was not slowing or even getting faster.

Unidirectional Data flow: Flux

Now that you have a component mechanism to define the interface, you need a mechanism to define how components are communicated between them and between the components and the data model. To this end, Facebook proposes a flux framework for managing data flow. Flux is a fairly loose conceptual framework that also conforms to react's simple and intuitive principles. Unlike the two-way data binding of most other MVC frameworks, flux advocates one-way data flow, that is, data flow from model to view forever.

Flux introduces the concept of dispatcher and action: Dispatcher is a global distributor responsible for receiving an action, and the store can hear the action on the Dispatcher and act accordingly. A simple understanding can be thought of as a global message-publishing subscription model. Action can come from one of the user's interface actions, such as clicking the Submit button, or from a server-side update to the data. When the data model changes, it triggers the refresh of the entire interface.

The definition of flux is very loose, in addition to the implementation of Facebook itself, there are many different implementations of flux in the community, the characteristics of the more popular include flexible, reflux, flummox and so on.

Make the data model simple: immutability

Immutability meaning is read-only data, react advocates the use of read-only data to establish a data model. This is another pretty crazy mechanism: all the data is read-only, and if you need to modify it, you can only generate a copy of the data that contains the new changes. Suppose you have the following data:

var employee = {  name: ' John ',  age:28};

If you want to change your age, you need to generate a new piece of data:

var updated = {  name:employee.name,  age:29};

In this way, the original employee object did not change, instead, produced a new updated object, reflecting the age has changed. The new updated object needs to be applied to the interface component to update the interface.

Read-only data is not a new Facebook invention, but a functional programming language that originates in Clojure, Scala, Haskell, and so on. Read-only data can make your code more secure and easier to maintain, and you no longer have to worry about the data being modified by some magical piece of code in a corner, and you won't have to debug it to find a place to change. In combination with react, read-only data allows react's components to determine whether they want to render again simply by comparing whether the object reference is equal. This can greatly improve performance in a complex interface.

For read-only data, Facebook developed a set of framework immutable.js that introduced the concept of read-only data to JavaScript and open source on GitHub. If you do not want to introduce such a large framework from the outset, React also provides a tool class plugin to help manage and manipulate read-only data: React.addons.update.

React ideas: React Native, React canvas, etc.

In the last few days of the Facebook F8 Developer conference, React native finally wanted to release it, and it extended the idea of React to native mobile development. Its slogan is "Learn Once, Write Anywhere", developers with react development experience will be able to seamlessly react native development. The powerful features of react such as component thinking, debugging tools, dynamic code loading can be applied to react Native. Believe that this will have a significant impact on future mobile development layouts.

The react is a perfect abstraction of the UI layer, and even the ability to fully dom the Web interface: Developers do not have to do any DOM operations. Therefore, this also makes it possible to replace the UI layer as a whole. React native The browser's DOM-based UI layer into native controls for iOS or Android. Instead, Flipboard changed the UI layer to canvas.

React Canvas is a set of front-end frames produced by Flipboard, and all interface elements are drawn through canvas, as Infoq has previously described. Flipboard pursues the ultimate in performance and user experience, and therefore hates the browser's slow DOM operation, discarding the DOM at its most drastic, and completely implements the entire UI control with canvas. Interested students may wish to have a try.

Summary

React is not a sudden jump from where, but to solve the front-end development of pain points. The simple principle of design also determines that the react has an extremely smooth learning curve, and developers can quickly get started and apply it to real projects. This paper summarizes and analyzes the design idea behind its related technology, hoping that through this angle we can make everyone have a general understanding of react, so that in the actual project development of react, follow the principle of simple and intuitive, and carry out high efficiency and high quality product development.

Resources
    1. React Official website: http://facebook.github.io/react/
    2. React Blog: http://facebook.github.io/react/blog/
    3. React Getting Started: http://ryanclark.me/getting-started-with-react/
    4. Disruptive front-End UI framework: React:http://www.infoq.com/cn/articles/subversion-front-end-ui-development-framework-react
    5. immutable.js:http://facebook.github.io/immutable-js/
    6. React native:http://facebook.github.io/react-native/
    7. flux:https://facebook.github.io/flux/
    8. Flux Frame comparison: Https://github.com/voronianski/flux-comparison
    9. React Developer Conference website: http://conf.reactjs.com/index.html
    10. React chat community on slack: http://reactiflux.com/

React's philosophy of design-the beauty of simplicity

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.