国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home WeChat Applet Mini Program Development How to use React virtual DOM

How to use React virtual DOM

May 31, 2018 pm 02:22 PM
react use virtual

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; i++) {
    var render = template;
    render = render.replace("{{className}}", "");
    render = render.replace("{{label}}", data[i].label);
    html += render;
  }
  ...
  container.innerHTML = html;
  ...
}

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:

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;
    }
  } 
  ... 
}

Looking at it this way, the performance of React is far better than native DOM operations.

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

HTML documents. 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.

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.

3. Virtual DOM VS MVVM?

Compared with React, other MVVM frameworks such as Angular, Knockout, Vue, and Avalon all use

data binding: 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):

  1. Dirty check: scope digest Necessary DOM update

  2. Dependency collection: Re-collect dependencies Necessary DOM update

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.

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.

  1. Initial rendering: Virtual DOM > Dirty Check>= Dependency Collection

  2. Small amount of data update: Dependency Collection>> Virtual DOM Optimization > Dirty Check (cannot be optimized) > Virtual DOM No Optimization

  3. Large data update: Dirty Check Optimization>= Dependency Collection Optimization> Virtual DOM (Cannot/No need to optimize )>> MVVM without optimization

  4. (This paragraph draws on the relevant answers from Zhihu)

  5. 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!

Statement of this Website
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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

React's Ecosystem: Libraries, Tools, and Best Practices React's Ecosystem: Libraries, Tools, and Best Practices Apr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

React: The Power of a JavaScript Library for Web Development React: The Power of a JavaScript Library for Web Development Apr 18, 2025 am 12:25 AM

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

Frontend Development with React: Advantages and Techniques Frontend Development with React: Advantages and Techniques Apr 17, 2025 am 12:25 AM

The advantages of React are its flexibility and efficiency, which are reflected in: 1) Component-based design improves code reusability; 2) Virtual DOM technology optimizes performance, especially when handling large amounts of data updates; 3) The rich ecosystem provides a large number of third-party libraries and tools. By understanding how React works and uses examples, you can master its core concepts and best practices to build an efficient, maintainable user interface.

The Future of React: Trends and Innovations in Web Development The Future of React: Trends and Innovations in Web Development Apr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

Understanding React's Primary Function: The Frontend Perspective Understanding React's Primary Function: The Frontend Perspective Apr 18, 2025 am 12:15 AM

React's main functions include componentized thinking, state management and virtual DOM. 1) The idea of ??componentization allows splitting the UI into reusable parts to improve code readability and maintainability. 2) State management manages dynamic data through state and props, and changes trigger UI updates. 3) Virtual DOM optimization performance, update the UI through the calculation of the minimum operation of DOM replica in memory.

React and Frontend Development: A Comprehensive Overview React and Frontend Development: A Comprehensive Overview Apr 18, 2025 am 12:23 AM

React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability

Using React with HTML: Rendering Components and Data Using React with HTML: Rendering Components and Data Apr 19, 2025 am 12:19 AM

Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics

The Power of React in HTML: Modern Web Development The Power of React in HTML: Modern Web Development Apr 18, 2025 am 12:22 AM

The application of React in HTML improves the efficiency and flexibility of web development through componentization and virtual DOM. 1) React componentization idea breaks down the UI into reusable units to simplify management. 2) Virtual DOM optimization performance, minimize DOM operations through diffing algorithm. 3) JSX syntax allows writing HTML in JavaScript to improve development efficiency. 4) Use the useState hook to manage state and realize dynamic content updates. 5) Optimization strategies include using React.memo and useCallback to reduce unnecessary rendering.

See all articles