search
HomeWeChat AppletMini Program DevelopmentHow to use React virtual DOM

How to use React virtual DOM

May 31, 2018 pm 02:22 PM
reactusevirtual

This time I will show you how to use React virtual DOM and what are the precautions for using React virtual DOM. The following is a practical case, let’s take a look.

In web development, data changes need to be reflected on the UI in real time. At this time, DOM operations need to be performed. However, complex or frequent DOM operations are usually the cause of performance bottlenecks. For this reason, React The mechanism of virtual DOM (Virtual DOM) is introduced.

1. What is virtual DOM?

In React, the result of render execution is not a real DOM node, but a lightweight

JavaScript object, which we call virtual DOM.

Virtual DOM is a highlight of React, with batching (batch processing) and efficient Diff algorithm. This allows us to "refresh" the entire page at any time without worrying about performance issues, and the virtual DOM ensures that only the actual DOM operations are performed on the truly changed parts of the interface. In actual development, you basically don’t need to care about how the virtual DOM works, but understanding its operating mechanism will not only help you better understand the

life cycle of React components, but will also be of great help in further optimizing React programs. help.

2. Virtual DOM VS directly operating the native DOM?

If there is no Virtual DOM, simply reset innerHTML directly. This operation is reasonable when all the data in a large list has changed. However, when only one row of data changes, it also needs to reset the entire innerHTML, which obviously causes a lot of waste.

Compare the redrawing process of innerHTML and Virtual DOM as follows:

innerHTML: render html string Recreate all DOM elements

Virtual DOM: render Virtual DOM diff necessary DOM updates

Compared with DOM operations, js calculation is very cheap. Virtual DOM render diff is obviously slower than rendering html strings, but it is still a pure js level calculation, which is still much cheaper than the subsequent DOM operations. Of course, someone has done verification and said that the performance of React is not as good as directly operating the real DOM. The code is as follows:

function Raw() {
  var data = _buildData(),
    html = "";
  ...
  for(var i=0; i<data.length>In this test case, a String containing 1000 Tags is constructed and added to the DOM tree. , but only one DOM operation was performed. However, in the actual development process, these 1,000 element updates may be distributed in 20 logical blocks, each logical block contains 50 elements. When the page needs to be updated, it will cause the DOM tree to be updated. The above code will approximately become It becomes the following format: <p style="text-align: left;"></p>
<pre class="brush:php;toolbar:false">function Raw() {
  var data = _buildData(), 
    html = ""; 
  ... 
  for(var i=0; i<data.length>Looking at it this way, the performance of React is far better than native DOM operations. <p style="text-align: left;"></p>Moreover, the DOM does not belong to Javascript at all (nor does it exist in the Javascript engine). Javascript is actually a very independent engine. DOM is actually a set of APIs introduced by the browser that allow Javascript to operate <p style="text-align: left;">HTML documents<a href="http://www.php.cn/code/5010.html" target="_blank">. In the era of just-in-time compilation, the overhead of calling DOM is very high. The execution of Virtual DOM is entirely in the Javascript engine, and there is no such overhead at all. </a></p>React.js has great performance advantages over direct manipulation of native DOM, largely due to the batching and diff of virtual DOM. Batching collects all DOM operations and submits them to the real DOM at once. The time complexity of the diff algorithm has also been reduced from O(n^3) of the standard Diff algorithm to O(n). I’ll leave this to the next blog post. <p style="text-align: left;"></p>
<p style="text-align: left;"><span style="color: #ff0000">3. Virtual DOM VS MVVM? <strong></strong></span></p>Compared with React, other MVVM frameworks such as Angular, Knockout, Vue, and Avalon all use <p style="text-align: left;">data binding<a href="http://www.php.cn/code/7876.html" target="_blank">: through Directive/Binding objects, observation The data changes and retains the reference to the actual DOM element, and performs corresponding operations when the data changes. MVVM's change checking is at the data level, while React's checking is at the DOM structure level. The performance of MVVM also differs based on the implementation principle of change detection: Angular's dirty check makes any change have a fixed cost of O (watcher count); Knockout/Vue/Avalon all use dependency collection, both at the js and DOM levels. Yes O(change): </a></p>
<ol class=" list-paddingleft-2">
<li>Dirty check: scope digest Necessary DOM update<p style="text-align: left;"></p>
</li>
<li>Dependency collection: Re-collect dependencies Necessary DOM update<p style="text-align: left;"></p>
</li>
</ol>
<p style="text-align: left;">As you can see, the most inefficient thing about Angular is that any small change has a performance cost related to the number of watchers. but! When all the data changes, Angular actually does not suffer. Dependency collection requires re-collection of dependencies during initialization and data changes. This cost can be almost ignored when a small amount of updates are made, but it will also cause a certain consumption when the amount of data is large. </p>
<p style="text-align: left;">When MVVM renders a list, since each row has its own data scope, each row usually has a corresponding ViewModel instance, or a slightly lighter "scope that uses prototype inheritance. " object, but there is a price. Therefore, initialization of MVVM list rendering is almost guaranteed to be slower than React, because creating ViewModel / scope instances is much more expensive than Virtual DOM. A common problem for all MVVM implementations here is how to effectively reuse already created ViewModel instances and DOM elements when the data source for list rendering changes, especially when the data is a brand new object. Without any reuse optimization, since the data is "new", MVVM actually needs to destroy all previous instances, recreate all instances, and finally render again! This is why the angular/knockout implementations linked in the title are relatively slow. In contrast, since React's change check is at the DOM structure level, even if it is brand new data, as long as the final rendering result has not changed, there is no need to do useless work. </p>
<p style="text-align: left;">Both Angular and Vue provide optimization mechanisms for list redrawing, which are "hints" to the framework on how to effectively reuse instances and DOM elements. For example, the same object in the database will become different objects in two front-end API calls, but they still have the same uid. At this time, you can prompt track by uid to let Angular know that the two objects are actually the same data. Then the instances and DOM elements corresponding to the original data can be reused, and only the changed parts need to be updated. Or, you can also directly track by $index to perform "in-place reuse": reuse directly based on the position in the array. In the example given in the question, if the angular implementation adds track by $index, subsequent redrawing will not be much slower than React. Even in the dbmonster test, Angular and Vue are faster than React after using track by $index: dbmon (note that the default version of Angular is not optimized, the optimized version is below) </p>
<p style="text-align: left;">When comparing performance, it is necessary to divide Understand the different occasions of initial rendering, small data update, and large data update. Virtual DOM, dirty checking MVVM, data collection MVVM have different performances and different optimization requirements on different occasions. In order to improve the performance of small data updates, Virtual DOM also needs targeted optimization, such as shouldComponentUpdate or immutable data. </p>
<ol class=" list-paddingleft-2">
<li><p style="text-align: left;">Initial rendering: Virtual DOM > Dirty Check>= Dependency Collection</p></li>
<li><p style="text-align: left;">Small amount of data update: Dependency Collection>> Virtual DOM Optimization > Dirty Check (cannot be optimized) > Virtual DOM No Optimization</p></li>
<li><p style="text-align: left;">Large data update: Dirty Check Optimization>= Dependency Collection Optimization> Virtual DOM (Cannot/No need to optimize )>> MVVM without optimization</p></li>
<li><p style="text-align: left;">(This paragraph draws on the relevant answers from Zhihu)</p></li>
</ol>
<p style="text-align: left;"><span style="color: #ff0000"><strong>four , Misunderstanding of React virtual DOM? </strong></span></p>
<p style="text-align: left;">React never said "React is faster than native DOM manipulation". React guarantees us that it can still provide us with decent performance without manual optimization. </p>
<p style="text-align: left;">React masks the underlying DOM operations and can describe our purpose in a more declarative way, making the code easier to maintain. The following is based on the answer on Zhihu: No framework can optimize DOM operations faster than purely manual operations, because the DOM operation layer of the framework needs to cope with any operations that may be generated by the upper-layer API, and its implementation must be universal. For any benchmark, I can write manual optimizations that are faster than any framework, but what's the point? When building a practical application, do you do manual optimization for every place? For maintainability reasons, this is obviously not possible. </p>
<p> I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! </p>
<p> Recommended reading: </p>
<p><a href="http://www.php.cn/xiaochengxu-399466.html" target="_blank"> Implementation of uploading pictures with back-end code in WeChat mini program </a><br></p>
<p><a href="http://www.php.cn/xiaochengxu-399464.html" target="_blank"> Practical practice of uploading pictures in WeChat mini program Case Analysis</a><br></p></data.length>

The above is the detailed content of How to use React virtual DOM. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools