For a better reading experience, please visit the original address: Portal

React

What’s the React

React was an internal project that originated at Facebook, which was not happy with all the JavaScript MVC frameworks on the market at the time, so they wrote their own and used it for Instagram. Once it was built, it worked pretty well, so it opened source in May 2013.

React is itself a JavaScript Library for building user interfaces. The React framework is a combination of React/ react-router and react-redux.

  • A “library” is a specific set (methods and functions) that is encapsulated and available to developers. The library has no control, but the control lies entirely with the user.
  • As the name implies, “framework” is a set of architecture, which provides users with a relatively complete solution based on their own characteristics. If users choose a set of framework, they need to make some adaptation according to the framework itself.

Why React?

This is a very interesting question, and also makes me confused and distressed. When I was still in school, I tried to build a simple blog system with Vue. The learning curve was smooth, and I was able to use it after learning some basic HTML/ CSS codes. However, since LEARNING React, the progress became relatively slow. Part of this was due to React’s innovative development model and the JSX syntax that made me feel awkward (the dishes were the original sin).

Vue writer You Yuxi answered “What are the advantages of Vue and React?” on Zhihu. The question is:

Here I can freely admit that React will be superior to Vue when it comes to history years from now. In fact, I, as a developer, really admire people like Jordan Walke and Sebastian Markbage for coming up with groundbreaking new directions from the development model level.

React was positioned from the start as a new way of thinking about UI development. When Pete Hunt first promoted React, his slogan was “Rethinking Best Practices”. Such positioning opened up some new ideas and attracted a group of early core users who liked to make changes. On this basis, many patterns that React developers consider common sense were incubated through community iteration. That’s what makes React great, and there’s a lot in Vue that was directly inspired by React. React dared to try it because it was Facebook. For a company of this size, the benefits of a qualitative upgrade at the infrastructure level are huge, and Facebook’s engineers are smart enough to be paid to change their habits. And external promotion, it is a big company only have “change the industry”.

Compared to “Why React?” React is definitely a breakthrough development model.

Is it because of the React componentization idea? It isn’t. I think this is somewhat similar to the concept of microservitization, which belongs to an era of ideological progress in computer engineering, a new mature solution for team collaboration, and an inevitable trend. Both Angular/ Vue and React naturally support the concept of componentization.

Is it because React performs better? I don’t think so. React may have taken off on the front end when it first came out because of its unique and efficient virtual DOM design, but now the front end technology is maturing. According to the comparison data in many places, React’s performance is not significantly different from that of other frameworks. And reflected in the peacetime development, such a comparison is not obvious speed difference, there is no much use.

There is also a view that React is good for building large projects. From my limited knowledge, I know that the React system has a lot of constraints and some unwritten conventions, just like some postures provided to users by default in SpringBoot. Naturally, it has strong engineering features, plus some conventional code styles or conventions. This makes Java ideal for large team projects. But the ability to develop large projects has always depended on the people, not the framework.

So the reason I’m convinced (I’m guessing) is that like Java, React architecture is mature enough, the community is very active, the answers to your problems can be easily found on the Internet, and there are some mature practices or wheels to solve a variety of problems. And React has another unique feature: You can develop Native mobile apps using React Native with relatively little pain.

React Core Concepts

Virtual DOM (Vitural Document Object Model)

To understand the concept of the “virtual DOM,” we first need to know what the “DOM” is. Forget about web pages for a moment, let’s imagine that we now need to write a program to change the following Markdown document:

# Title
## subtitle - 1
content - 1
## subtitle - 2
content - 2Copy the code

For example, I now want to change the content – 2 content, so I will need one line of traversal till finally through it, the content change of operation about the same, so if I want to optimize the this lookup operation, the most simple idea is to keep it trees to reduce the height, increase the efficiency.

The concept of the DOM

DOM is the abbreviation of English Document Object Model, that is, Document Object Model. It is a cross-platform, programming language-independent API that treats AN HTML, XHTML, or XML document as a tree structure, and each node as an object that can be manipulated by a programming language to change the structure of the document and map it to its presentation. DOM was originally interwoven with JavaScript, but they eventually evolved into two separate entities. DOM is designed to be independent of a particular programming language, and while JavaScript is used most of the time, other languages (such as Python) can be used as well.

Suppose you have an HTML code that looks like this:

< HTML > < head > < title > document title < / title > < / head > < body > < a href = "" > link < / a > < h1 > title < / h1 > < / body > < / HTML >Copy the code

It should end up like this tree:

Instead of discussing the types and methods of DOM nodes, we just need to get a general idea of the DOM.

The process by which the browser renders the DOM

We can take a quick look at how the browser renders the DOM:

  1. Parsing HTML to build a DOM tree;
  2. Parsing CSS and combining DOM tree to form Reander tree;
  3. Render tree (Layout/ reflow) to determine the size, location and other information of each node;
  4. Render tree (Paint), Render the page pixel information;
  5. The browser sends each layer of information to the GPU, which then composes each layer and displays it on the screen.

Why is DOM manipulation slow

Strictly speaking, simply manipulating the DOM is not slow, and there are certain conditions for it to be slow.

Imagine manipulating the DOM multiple times in an event loop. Sometimes you want the JS code to get the latest DOM node information immediately. Then the browser has to suspend the JS engine and call the DOM engine to compute and render the latest DOM to get the latest DOM node information. Then reactivate the JS engine to continue with the subsequent operations.

Predictably, this requires not only multiple engine switches, but also multiple calculations of the layout and DOM redrawing. In fact, paint is a time-consuming process, while layout is a more time-consuming process. We are not sure whether layout is top-down or bottom-up, and even a layout will involve the recalculation of the entire document layout.

However, layout is inevitable, so we mainly minimize the number of layout.

Therefore, reducing engine switching frequency and DOM change scale is the key to DOM performance optimization scheme!

Steps of Virtual DOM algorithm

Virtual DOM solves the above problems. Its essence is to use JS objects to simulate our real DOM tree. Its algorithm is roughly as follows:

  1. Use JavaScript object mapping to form a DOM tree structure, and then use this tree to build a real DOM tree, inserted into the document;
  2. When the state changes, a new object tree is reconstructed, and then the new tree is compared with the old tree (Diff algorithm) to record the differences between the two trees.
  3. The view is updated by applying the differences recorded in step 2 to the actual DOM tree built in Step 1.

The difference between the virtual DOM and the real DOM

We can see the difference between the two:

  1. When changing multiple states and affecting the layout of multiple nodes, the JS objects in memory are frequently modified, and then the parts that need to be changed in the real DOM are compared and modified at one time. Finally, typesetting and redrawing are carried out in the real DOM to reduce the loss of excessive DOM node typesetting and redrawing.
  2. The frequent typesetting and redrawing of the real DOM is quite inefficient;
  3. Virtual DOM can effectively reduce the redrawing and typesetting of large areas (real DOM nodes), because the final DOM is different from the real DOM and can only render parts (same as 2).

Loss calculation using virtual DOM:

Total loss = virtual DOM addition, deletion and modification + (related to the efficiency of Diff algorithm) real DOM difference addition, deletion and modification + (fewer nodes) typesetting and redrawing

Loss calculation using the real DOM directly:

Total loss = complete addition, deletion and modification of the real DOM + (possibly more nodes) typesetting and redrawing

The Diff algorithm

The core of the virtual DOM is the Diff, which automatically calculates what needs to be adjusted, and then only changes the areas that need to be adjusted, saving not “little speed” like runtime speed, but “total speed” like development speed/maintenance speed/logic brevity.

However, the virtual DOM is also fast under relative conditions. Here is a quote from @Youyucrea.com in question: “The Internet says that operating the real DOM is slow, but the test results are faster than React. Why?” The answer is:

Don’t be fooled into thinking that Virtual DOM is fast, diff is not free, batching and MVVM can do it, and eventually patch will have to use native apis. In my opinion, the real value of Virtual DOM has never been performance, but 1) it opens the door to functional UI programming; 2) Can render to backend other than DOM, such as ReactNative.

Diff can be roughly divided into three types:

  • Tree Diff: The process of comparing the old and new DOM trees layer by layer is called Tree Diff. When the comparison of the whole DOM layer by layer is completed, all the elements that need to be updated as needed must be found.
  • Component Diff:The Tree Diff comparison is called Component Diff for each layer:
    • If the type of the component is the same before and after the comparison, the component does not need to be updated.
    • If the component type is different before and after the comparison, remove the old component, create a new component, and add it to the page.
  • Element Diff: When comparing components, if two components of the same type are compared at the Element level, this is called Element Diff.

Third, Hello World

  • Quote from: http://www.ruanyifeng.com/blog/2015/03/react.html – nguyen other tutorial – introduction to React instance

React/React/React

<! DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <title>Hello React! < / title > < script SRC = "https://cdn.staticfile.org/react/16.4.0/umd/react.development.js" > < / script > < script SRC = "https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js" > < / script > < script SRC = "https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js" > < / script > < / head > < body > < div id = "example" > < / div > <script type="text/babel"> ReactDOM.render( <h1>Hello, world! </h1>, document.getElementById('example') ); </script> </body> </html>Copy the code

There are two things to note about the code above. First of all, the last one