search
HomeWeb Front-endFront-end Q&AWhat 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])
        );
      }
    }
  }

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
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
Mastering CSS Selectors: Class vs. ID for Efficient StylingMastering CSS Selectors: Class vs. ID for Efficient StylingMay 16, 2025 am 12:19 AM

The use of class selectors and ID selectors depends on the specific use case: 1) Class selectors are suitable for multi-element, reusable styles, and 2) ID selectors are suitable for unique elements and specific styles. Class selectors are more flexible, ID selectors are faster to process but may affect code maintenance.

HTML5 Specification: Exploring the Key Goals and MotivationsHTML5 Specification: Exploring the Key Goals and MotivationsMay 16, 2025 am 12:19 AM

ThekeygoalsandmotivationsbehindHTML5weretoenhancesemanticstructure,improvemultimediasupport,andensurebetterperformanceandcompatibilityacrossdevices,drivenbytheneedtoaddressHTML4'slimitationsandmeetmodernwebdemands.1)HTML5aimedtoimprovesemanticstructu

CSS IDs and Classes : a simple guideCSS IDs and Classes : a simple guideMay 16, 2025 am 12:18 AM

IDsareuniqueandusedforsingleelements,whileclassesarereusableformultipleelements.1)UseIDsforuniqueelementslikeaspecificheader.2)Useclassesforconsistentstylingacrossmultipleelementslikebuttons.3)BecautiouswithspecificityasIDsoverrideclasses.4)Useclasse

HTML5 Goals: Understanding the Key Objectives of the SpecificationHTML5 Goals: Understanding the Key Objectives of the SpecificationMay 16, 2025 am 12:16 AM

HTML5aimstoenhancewebaccessibility,interactivity,andefficiency.1)Itsupportsmultimediawithoutplugins,simplifyinguserexperience.2)Semanticmarkupimprovesstructureandaccessibility.3)Enhancedformhandlingincreasesusability.4)Thecanvaselementenablesdynamicg

Is it difficult to use HTML5 to achieve its goals?Is it difficult to use HTML5 to achieve its goals?May 16, 2025 am 12:06 AM

HTML5isnotparticularlydifficulttousebutrequiresunderstandingitsfeatures.1)Semanticelementslike,,,andimprovestructure,readability,SEO,andaccessibility.2)Multimediasupportviaandelementsenhancesuserexperiencewithoutplugins.3)Theelementenablesdynamic2Dgr

CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!