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)

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 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 real-time data processing applications using React and Apache Kafka How to build real-time data processing applications using React and Apache Kafka Sep 27, 2023 pm 02:25 PM

How to use React and Apache Kafka to build real-time data processing applications Introduction: With the rise of big data and real-time data processing, building real-time data processing applications has become the pursuit of many developers. The combination of React, a popular front-end framework, and Apache Kafka, a high-performance distributed messaging system, can help us build real-time data processing applications. This article will introduce how to use React and Apache Kafka to build real-time data processing applications, and

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

How to use React to develop a responsive backend management system How to use React to develop a responsive backend management system Sep 28, 2023 pm 04:55 PM

How to use React to develop a responsive backend management system. With the rapid development of the Internet, more and more companies and organizations need an efficient, flexible, and easy-to-manage backend management system to handle daily operations. As one of the most popular JavaScript libraries currently, React provides a concise, efficient and maintainable way to build user interfaces. This article will introduce how to use React to develop a responsive backend management system and give specific code examples. Create a React project first

See all articles