Table of Contents
2. React’s Diff algorithm
2. What is React diff algorithm? " >2. What is React diff algorithm?
3. Diff strategy" >3. Diff strategy
##5. component diff :" >##5. component diff :
3. Development suggestions based on Diff
Home Web Front-end Front-end Q&A What is react's diff method?

What is react's diff method?

Jan 03, 2023 pm 01:50 PM
react

The diff method of react can be used to find the difference between two objects, with the purpose of reusing nodes as much as possible; the diff algorithm is the specific implementation of reconciliation, and reconciliation refers to converting the Virtual DOM tree into The minimal manipulation process of the Actual DOM tree.

What is react's diff method?

The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.

What is the diff method of react?

1. The role of Diff algorithm

Rendering the real DOM is very expensive. Sometimes we modify a certain data and render it directly to the real DOM. Will cause the entire DOM tree to be redrawn and rearranged. We hope to only update the small piece of DOM we modified, not the entire DOM. The diff algorithm helps us achieve this.
The essence of the diff algorithm is to find the difference between two objects, with the purpose of reusing nodes as much as possible.
Note: The object mentioned here actually refers to the virtual dom (virtual dom tree) in vue, that is, using js objects to represent the dom structure in the page.

2. React’s Diff algorithm

1、 What is Reconciliation##?

The minimum number of to convert a Virtual DOM tree into an Actual DOM tree The process of operation is called reconciliation.

2. What is React diff algorithm?

diff algorithm is the specific implementation of reconciliation.

3. Diff strategy

##​

React uses three major strategies to transform O(n3) complexity into O(n) complexity      

(1) Strategy One (##tree diff): There are very few cross-level movement operations of DOM nodes in the Web UI and can be ignored.

    (2) Strategy 2 (component diff):Two components with the same class generate a similar tree structure, Two components with different classes Generate different tree structures.

(3) Strategy Three (element diff): For a group of child nodes at the same level, they are distinguished by unique ids.

What is reacts diff method?

4. Tree diff:

(1) React uses updateDepth to perform hierarchical control on the Virtual DOM tree.

(2) Compare the trees hierarchically, the two trees only compare Nodes # at the same level are compared. If the node does not exist, the node and its child nodes will be completely deleted and will not be compared further.

#(3) Only one traversal is needed to complete the comparison of the entire DOM tree.

What will Diff do if a cross-level operation occurs on a DOM node?

Answer: Tree DIFF traverses each layer of the tree. If a component no longer exists, it will be destroyed directly. As shown in the figure, the left side is the old attribute and the right side is the new attribute. The first layer is the R component, which is exactly the same and will not change. The second layer enters Component DIFF and the same type of components continues to be compared. It is found that the A component does not exist, so directly Delete components A, B, and C; continue to the third layer and re-create components A, B, and C.

What is reacts diff method?

As shown in the picture above, the entire tree with A as the root node will be recreated instead of moved, so it is officially recommended not to perform DOM Nodes operate across levels, and nodes can be hidden and displayed through CSS instead of actually removing or adding DOM nodes.

##5. component diff :

React has three strategies for comparing different components

(1) Same type For the two components, just continue to compare the Virtual DOM tree according to the original strategy (hierarchical comparison).

(2) For two components of the same type, when component A changes to component B, the Virtual DOM may not change at all. If you know this (the Virtual DOM does not change during the transformation process), It can save a lot of calculation time, so users can use shouldComponentUpdate() to judge whether judgment calculation is needed.

(3) Different types of components, determine a component (to be changed) as a dirty component, thereby replacing all nodes of the entire component .

What is reacts diff method?

Notice: As shown in the figure above, When component D changes to component G, even if the two components have similar structures, Once React determines that D and G are components of different types, it will not compare Instead of directly deleting component D and re-creating component G and its sub-nodes. Although when two components are of different types but have similar structures, performing diff algorithm analysis will affect performance. However, after all, the situation where different types of components have similar DOM trees rarely occurs in the actual development process, so this extreme factor It is difficult to have a significant impact on the actual development process.

6、##element diff

##When nodes are at the same level, diff provides three node operations: Delete, insert, move .

Insert ##:Component C is not in the set (A,B) and needs to be inserted

##Delete: ##(1) Component D is in the set (A, B, D), but the node of D has changed and cannot be reused and updated, so the old D needs to be deleted and a new one needs to be created.

(2) Component D was previously in the set (A, B, D), but the set became a new set (A, B), D It needs to be deleted.

Move:

Component D is already in the collection ( A, B, C, D), and when the set is updated, D is not updated, but the position changes. For example, in the new set (A, D, B, C), D is in the second one. There is no need to do it like a traditional diff. Let Compare the second B of the old set with the second D of the new set, delete the B at the second position, insert D at the second position, and add a unique key (for the same group of child nodes at the same level) To differentiate, just move.

Move

situation 1: How to move the node when the same node exists in the old and new sets but in different positions

What is reacts diff method?

(1) B does not move, no further details, update l astIndex=1

(2) The new collection obtains E and finds that the old one does not exist, so it creates E at the position of lastIndex=1 and updates lastIndex=1

(3) The new set gets C, C does not move, update lastIndex=2

(4) The new set gets A, A moves, same as above, update lastIndex=2

(5) After comparing the new set, traverse the old set. It is judged that the new set does not have elements, but the old set has elements (such as D, the new set does not have it, but the old set has it), D is found, D is deleted, and the diff operation ends.


Code for Diff algorithm implementation in React:

_updateChildren: function(nextNestedChildrenElements, transaction, context) {
    var prevChildren = this._renderedChildren;
    var removedNodes = {};
    var mountImages = [];
    // 获取新的子元素数组
    var nextChildren = this._reconcilerUpdateChildren(
      prevChildren,
      nextNestedChildrenElements,
      mountImages,
      removedNodes,
      transaction,
      context
    );
    if (!nextChildren && !prevChildren) {
      return;
    }
    var updates = null;
    var name;
    var nextIndex = 0;
    var lastIndex = 0;
    var nextMountIndex = 0;
    var lastPlacedNode = null;
    for (name in nextChildren) {
      if (!nextChildren.hasOwnProperty(name)) {
        continue;
      }
      var prevChild = prevChildren && prevChildren[name];
      var nextChild = nextChildren[name];
      if (prevChild === nextChild) {
        // 同一个引用,说明是使用的同一个component,所以我们需要做移动的操作
        // 移动已有的子节点
        // NOTICE:这里根据nextIndex, lastIndex决定是否移动
        updates = enqueue(
          updates,
          this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)
        );
        // 更新lastIndex
        lastIndex = Math.max(prevChild._mountIndex, lastIndex);
        // 更新component的.mountIndex属性
        prevChild._mountIndex = nextIndex;
      } else {
        if (prevChild) {
          // 更新lastIndex
          lastIndex = Math.max(prevChild._mountIndex, lastIndex);
        }

        // 添加新的子节点在指定的位置上
        updates = enqueue(
          updates,
          this._mountChildAtIndex(
            nextChild,
            mountImages[nextMountIndex],
            lastPlacedNode,
            nextIndex,
            transaction,
            context
          )
        );
        nextMountIndex++;
      }
      // 更新nextIndex
      nextIndex++;
      lastPlacedNode = ReactReconciler.getHostNode(nextChild);
    }
    // 移除掉不存在的旧子节点,和旧子节点和新子节点不同的旧子节点
    for (name in removedNodes) {
      if (removedNodes.hasOwnProperty(name)) {
        updates = enqueue(
          updates,
          this._unmountChild(prevChildren[name], removedNodes[name])
        );
      }
    }
  }
Copy after login

3. Development suggestions based on Diff

Based on tree diff:

  • When developing components, pay attention to maintaining the stability of the DOM structure; that is, dynamically operate the DOM structure as little as possible, especially mobile operations .
  • When the number of nodes is too large or the number of page updates is too many, the page lag will be more obvious.
  • At this time, you can hide or show nodes through CSS instead of actually removing or adding DOM nodes.

Based on component diff:

  • Pay attention to using shouldComponentUpdate() to reduce unnecessary updates of components.
  • Similar structures should be encapsulated into components as much as possible, which not only reduces the amount of code, but also reduces the performance consumption of component diff.

Based on element diff:

  • For list structures, try to reduce operations like moving the last node to the head of the list. When the number of nodes exceeds When the update operation is large or too frequent, it will affect the rendering performance of React to a certain extent.

Recommended learning: "react video tutorial"

The above is the detailed content of What is react's diff method?. 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

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 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)

How to build a real-time chat app with React and WebSocket How to build a real-time chat app with React and WebSocket Sep 26, 2023 pm 07:46 PM

How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Sep 28, 2023 am 10:48 AM

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to build simple and easy-to-use web applications with React and Flask How to build simple and easy-to-use web applications with React and Flask Sep 27, 2023 am 11:09 AM

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging app with React and RabbitMQ How to build a reliable messaging app with React and RabbitMQ Sep 28, 2023 pm 08:24 PM

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

React code debugging guide: How to quickly locate and solve front-end bugs React code debugging guide: How to quickly locate and solve front-end bugs Sep 26, 2023 pm 02:25 PM

React code debugging guide: How to quickly locate and resolve front-end bugs Introduction: When developing React applications, you often encounter a variety of bugs that may crash the application or cause incorrect behavior. Therefore, mastering debugging skills is an essential ability for every React developer. This article will introduce some practical techniques for locating and solving front-end bugs, and provide specific code examples to help readers quickly locate and solve bugs in React applications. 1. Selection of debugging tools: In Re

React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to build a fast data analysis application using React and Google BigQuery How to build a fast data analysis application using React and Google BigQuery Sep 26, 2023 pm 06:12 PM

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

How to package and deploy front-end applications using React and Docker How to package and deploy front-end applications using React and Docker Sep 26, 2023 pm 03:14 PM

How to use React and Docker to package and deploy front-end applications. Packaging and deployment of front-end applications is a very important part of project development. With the rapid development of modern front-end frameworks, React has become the first choice for many front-end developers. As a containerization solution, Docker can greatly simplify the application deployment process. This article will introduce how to use React and Docker to package and deploy front-end applications, and provide specific code examples. 1. Preparation Before starting, we need to install

See all articles