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
React and HTML: Rendering Data and Handling EventsReact and HTML: Rendering Data and Handling EventsApr 20, 2025 am 12:21 AM

React efficiently renders data through state and props, and handles user events through the synthesis event system. 1) Use useState to manage state, such as the counter example. 2) Event processing is implemented by adding functions in JSX, such as button clicks. 3) The key attribute is required to render the list, such as the TodoList component. 4) For form processing, useState and e.preventDefault(), such as Form components.

The Backend Connection: How React Interacts with ServersThe Backend Connection: How React Interacts with ServersApr 20, 2025 am 12:19 AM

React interacts with the server through HTTP requests to obtain, send, update and delete data. 1) User operation triggers events, 2) Initiate HTTP requests, 3) Process server responses, 4) Update component status and re-render.

React: Focusing on the User Interface (Frontend)React: Focusing on the User Interface (Frontend)Apr 20, 2025 am 12:18 AM

React is a JavaScript library for building user interfaces that improves efficiency through component development and virtual DOM. 1. Components and JSX: Use JSX syntax to define components to enhance code intuitiveness and quality. 2. Virtual DOM and Rendering: Optimize rendering performance through virtual DOM and diff algorithms. 3. State management and Hooks: Hooks such as useState and useEffect simplify state management and side effects handling. 4. Example of usage: From basic forms to advanced global state management, use the ContextAPI. 5. Common errors and debugging: Avoid improper state management and component update problems, and use ReactDevTools to debug. 6. Performance optimization and optimality

React in the HTML: Building Interactive User InterfacesReact in the HTML: Building Interactive User InterfacesApr 20, 2025 am 12:05 AM

React can be embedded in HTML to enhance or completely rewrite traditional HTML pages. 1) The basic steps to using React include adding a root div in HTML and rendering the React component via ReactDOM.render(). 2) More advanced applications include using useState to manage state and implement complex UI interactions such as counters and to-do lists. 3) Optimization and best practices include code segmentation, lazy loading and using React.memo and useMemo to improve performance. Through these methods, developers can leverage the power of React to build dynamic and responsive user interfaces.

React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 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.

React: A Powerful Tool for Building UI ComponentsReact: A Powerful Tool for Building UI ComponentsApr 19, 2025 am 12:22 AM

React is a JavaScript library for building user interfaces. Its core idea is to build UI through componentization. 1. Components are the basic unit of React, encapsulating UI logic and styles. 2. Virtual DOM and state management are the key to component work, and state is updated through setState. 3. The life cycle includes three stages: mount, update and uninstall. The performance can be optimized using reasonably. 4. Use useState and ContextAPI to manage state, improve component reusability and global state management. 5. Common errors include improper status updates and performance issues, which can be debugged through ReactDevTools. 6. Performance optimization suggestions include using memo, avoiding unnecessary re-rendering, and using us

Using React with HTML: Rendering Components and DataUsing React with HTML: Rendering Components and DataApr 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

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft