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 lightweightJavaScript 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 thelife 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; i++) { var render = template; render = render.replace("{{className}}", ""); render = render.replace("{{label}}", data[i].label); html += render; } ... container.innerHTML = html; ... }
function Raw() { var data = _buildData(), html = ""; ... for(var i=0; i<data.length; i++) { var render = template; render = render.replace("{{className}}", ""); render = render.replace("{{label}}", data[i].label); html += render; if(!(i % 50)) { container.innerHTML = html; } } ... }
3. Virtual DOM VS MVVM?
Compared with React, other MVVM frameworks such as Angular, Knockout, Vue, and Avalon all useAs 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.
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.
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)
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.
Initial rendering: Virtual DOM > Dirty Check>= Dependency Collection
Small amount of data update: Dependency Collection>> Virtual DOM Optimization > Dirty Check (cannot be optimized) > Virtual DOM No Optimization
Large data update: Dirty Check Optimization>= Dependency Collection Optimization> Virtual DOM (Cannot/No need to optimize )>> MVVM without optimization
(This paragraph draws on the relevant answers from Zhihu)
four , Misunderstanding of React virtual DOM?
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.
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.
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!
Recommended reading:
Implementation of uploading pictures with back-end code in WeChat mini program
Practical practice of uploading pictures in WeChat mini program Case Analysis
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!