search
HomeWeb Front-endJS TutorialWhat algorithms does the React framework have? Detailed explanation of the algorithm of react framework

This article mainly tells a detailed explanation of the principles of the react framework. There is also a lot of in-depth understanding of react below. Let us take a look at this article now

I have been working on React for more than 2 years. I love and hate this framework. Everyone is familiar with its advantages, but its shortcomings are gradually exposed. In a large-scale project , when combined with third-party frameworks such as Redux and ReactRouter, the amount of complex business code will become very large (the front-end code is often 1.5 times the previous size). If the underlying design is not good in the early stage, you will often face the problem of low development efficiency. The following summarizes some core concepts of the React framework, I hope it will be helpful to everyone:

React diff algorithm

React’s diff algorithm It is the biggest reliance of Virtual DOM. We all know that the performance of a page is generally determined by the rendering speed and number of renderings. How to maximize the use of the diff algorithm for development? Let's first look at how it works.

Traditional diff algorithm

Calculate the minimum operation required to convert one tree structure into another tree structure. The traditional diff algorithm compares nodes sequentially through loop recursion, which is inefficient and complex. The degree reaches O(n^3), where n is the total number of nodes in the tree. In other words, if you want to display 1,000 nodes, you will have to perform billions of comparisons in sequence. This performance consumption is unacceptable for front-end projects.

Core Algorithm

As seen above, the complexity of the traditional diff algorithm is O(n^3), which obviously cannot meet the performance requirements. And React transforms O(n^3) complexity problems into O(n) complexity problems by formulating bold strategies. How did he do that?

tree diff

There are very few cross-level movement operations of DOM nodes in Web UI and can be ignored. React has made a concise and clear optimization of the tree algorithm, that is, hierarchical comparison of trees. Two trees will only compare nodes at the same level. As shown in the figure below:

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

React uses updateDepth to control the level of the Virtual DOM tree. Only DOM nodes in the same color box will be compared, that is, the same color will be compared. All child nodes under a parent node. When it is found that a node no longer exists, the node and its sub-nodes will be completely deleted and will not be used for further comparisons. In this way, only one traversal of the tree is needed to complete the comparison of the entire DOM tree.

// tree diff算法实现updateChildren: function(nextNestedChildrenElements, transaction, context) {
  updateDepth++;  var errorThrown = true;  try {    this._updateChildren(nextNestedChildrenElements, transaction, context);
    errorThrown = false;
  } finally {
    updateDepth--;    if (!updateDepth) {      if (errorThrown) {
        clearQueue();
      } else {
        processQueue();
      }
    }
  }
}

Why should we reduce the cross-level operations of DOM nodes?

As shown below, the A node (including its sub-nodes) is moved entirely to the D node. Since React will only simply consider the position transformation of nodes at the same level, and for nodes at different levels, only creation and deletion are required. operate. When the root node finds that A has disappeared in the child node, it will destroy A directly; when D finds that there is an additional child node A, it will create a new A (including child nodes) as its child node. At this time, the execution of React diff is: create A -> create B -> create C -> delete A.

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

It can be found that when a node moves across levels, the imaginary move operation will not occur, but the tree with A as the root node will be completely re- Create, which is an operation that affects React performance.

component diff

Two components with the same class will generate similar tree structures, and two components with different classes will generate different tree structures.

  • If they are components of the same type, continue to compare virtual DOM tree according to the original strategy.

  • If not, the component will be judged as dirty component, thereby replacing all child nodes under the entire component.

  • For the same type of component, there may be no change in its Virtual DOM. If you can know this for sure, you can save a lot of diff operation time, so React Allows users to determine whether the component needs to be diffed through shouldComponentUpdate().

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

As shown above, when component D changes to component G, even if the two component have similar structures, once React determines D and G is a different type of component, so the structures of the two will not be compared, but component D will be deleted directly and component G and its sub-nodes will be re-created. Although React diff will affect performance when two component are different types but have similar structures, as the React official blog says: Different types of component There are very few opportunities for similar DOM tree, so it is difficult for such extreme factors to have a significant impact on the implementation and development process.

element diff

For a group of child nodes at the same level, they can be distinguished by a unique id. React proposes an optimization strategy: developers are allowed to add unique keys to distinguish the same group of child nodes at the same level. Although it is only a small change, the performance has undergone earth-shaking changes!

The nodes contained in the new and old sets are as shown in the figure below. The new and old sets are compared by diff. Through the key, it is found that the nodes in the new and old sets are the same nodes, so there is no need to delete and create nodes. , you only need to move the positions of the nodes in the old set and update them to the positions of the nodes in the new set. At this time, the diff result given by React is: B and D do not perform any operations, and A and C perform moving operations.

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

Development Suggestions

(1)[Based on tree diff] When developing components, maintaining a stable DOM structure helps maintain overall performance. In other words, do as little dynamic manipulation of the DOM structure as possible, especially movement operations. When the number of nodes is too large or the number of page updates is too large, the page freeze phenomenon is more obvious. You can hide or show nodes via CSS without actually removing or adding DOM nodes.

(2)[Based on component diff] When developing components, pay attention to using shouldComponentUpdate() to reduce unnecessary updates of components. In addition, 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.

(3)[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 is too large or update operations are too frequent, It will affect the rendering performance of React to a certain extent.

React Lifecycle

The life cycle of React can be divided into four situations:

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

  • When it is loaded for the first time component, execute getDefaultProps, getInitialState, componentWillMount, render and componentDidMount in order;

  • When unloading a component, execute componentWillUnmount;

  • When reloading a component, execute getInitialState# in order. ##, componentWillMount, render and componentDidMount, but does not execute getDefaultProps;

  • When the component is rendered again, the component receives the updated status. At this time,

    componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate, render and componentDidUpdate.

Three states of React components

State 1: MOUNTING

mountComponent Responsible for managing in the life cycle getInitialState, componentWillMount, render, and componentDidMount.

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

State 2: RECEIVE_PROPS

updateComponent Responsible for managing componentWillReceiveProps, shouldComponentUpdate in the life cycle , componentWillUpdate, render and componentDidUpdate.

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

State 3: UNMOUNTING

unmountComponent is responsible for managing componentWillUnmount in the life cycle. (If you want to see more, go to the PHP Chinese website React Reference Manual column to learn)

First set the status to

UNMOUNTING, if componentWillUnmount## exists #, then execute; if setState is called in componentWillUnmount at this time, reRender will not be triggered. The update status is NULL, and the component uninstallation operation is completed. The implementation code is as follows: <pre class='brush:php;toolbar:false;'>// 卸载组件unmountComponent: function() { // 设置状态为 UNMOUNTING this._compositeLifeCycleState = CompositeLifeCycle.UNMOUNTING; // 如果存在 componentWillUnmount,则触发 if (this.componentWillUnmount) { this.componentWillUnmount(); } // 更新状态为 null this._compositeLifeCycleState = null; this._renderedComponent.unmountComponent(); this._renderedComponent = null; ReactComponent.Mixin.unmountComponent.call(this); }</pre><h2 id="React生命周期总结">React生命周期总结</h2> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/939/139/606/1536648897123010.png?x-oss-process=image/resize,p_40" class="lazy" title="1536648897123010.png" alt="What algorithms does the React framework have? Detailed explanation of the algorithm of react framework"></p> <table> <thead><tr class="firstRow"> <th>生命周期</th> <th>调用次数</th> <th>能否使用setState()</th> </tr></thead> <tbody> <tr> <td>getDefaultProps</td> <td>1</td> <td>否</td> </tr> <tr> <td>getInitialState</td> <td>1</td> <td>否</td> </tr> <tr> <td>componentWillMount</td> <td>1</td> <td>是</td> </tr> <tr> <td>render</td> <td>>=1</td> <td>否</td> </tr> <tr> <td>componentDidMount</td> <td>1</td> <td>是</td> </tr> <tr> <td>componentWillReceiveProps</td> <td>>=0</td> <td>是</td> </tr> <tr> <td>shouldComponentUpdate</td> <td>>=0</td> <td>否</td> </tr> <tr> <td>componentWillUpdate</td> <td>>=0</td> <td>否</td> </tr> <tr> <td>componentDidUpdate</td> <td>>=0</td> <td>否</td> </tr> <tr> <td>componentWillUnmount</td> <td>1</td> <td>否</td> </tr> <tr> <td>componentDidUnmount</td> <td>1</td> <td>否</td> </tr> </tbody> </table> <h1 id="setState实现机制">setState实现机制</h1> <p><code>setStateReact框架的核心方法之一,下面介绍一下它的原理:

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

// 更新 statesetState: function(partialState, callback) {
  // 合并 _pendingState
  this.replaceState(
    assign({}, this._pendingState || this.state, partialState),
    callback
  );
},

当调用 setState 时,会对 state 以及 _pendingState 更新队列进行合并操作,但其实真正更新 state 的幕后黑手是replaceState

// 更新 statereplaceState: function(completeState, callback) {
  validateLifeCycleOnReplaceState(this);  // 更新队列
  this._pendingState = completeState;  // 判断状态是否为 MOUNTING,如果不是,即可执行更新
  if (this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING) {
    ReactUpdates.enqueueUpdate(this, callback);
  }
},

replaceState 会先判断当前状态是否为 MOUNTING,如果不是即会调用 ReactUpdates.enqueueUpdate 执行更新。

当状态不为 MOUNTINGRECEIVING_PROPS 时,performUpdateIfNecessary 会获取 _pendingElement_pendingState_pendingForceUpdate,并调用 updateComponent 进行组件更新。

// 如果存在 _pendingElement、_pendingState、_pendingForceUpdate,则更新组件performUpdateIfNecessary: function(transaction) {
  var compositeLifeCycleState = this._compositeLifeCycleState;  // 当状态为 MOUNTING 或 RECEIVING_PROPS时,则不更新
  if (compositeLifeCycleState === CompositeLifeCycle.MOUNTING ||
      compositeLifeCycleState === CompositeLifeCycle.RECEIVING_PROPS) {    return;
  }  var prevElement = this._currentElement;  var nextElement = prevElement;  if (this._pendingElement != null) {
    nextElement = this._pendingElement;    this._pendingElement = null;
  }  // 调用 updateComponent
  this.updateComponent(
    transaction,
    prevElement,
    nextElement
  );
}

如果在 shouldComponentUpdatecomponentWillUpdate 中调用 setState,此时的状态已经从 RECEIVING_PROPS -> NULL,则 performUpdateIfNecessary 就会调用 updateComponent 进行组件更新,但 updateComponent 又会调用 shouldComponentUpdatecomponentWillUpdate,因此造成循环调用,使得浏览器内存占满后崩溃。

开发建议

不建议在 getDefaultPropsgetInitialStateshouldComponentUpdatecomponentWillUpdaterendercomponentWillUnmount 中调用 setState,特别注意:不能在 shouldComponentUpdatecomponentWillUpdate中调用 setState,会导致循环调用。

本篇文章到这就结束了(想看更多就到PHP中文网React使用手册栏目中学习),有问题的可以在下方留言提问。

The above is the detailed content of What algorithms does the React framework have? Detailed explanation of the algorithm of react framework. 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
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)