


What 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
andReactRouter
, 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:
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.
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, soReact
Allows users to determine whether the component needs to be diffed throughshouldComponentUpdate()
.
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.
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:
When it is loaded for the first time component, execute
getDefaultProps
,getInitialState
,componentWillMount
,render
andcomponentDidMount
in order;When unloading a component, execute
componentWillUnmount
;When reloading a component, execute
getInitialState# in order. ##,
componentWillMount,
renderand
componentDidMount, but does not execute
getDefaultProps;
- When the component is rendered again, the component receives the updated status. At this time,
componentWillReceiveProps
,
shouldComponentUpdate,
componentWillUpdate,
renderand
componentDidUpdate.
mountComponent Responsible for managing
in the life cycle getInitialState,
componentWillMount,
render, and
componentDidMount.
updateComponent Responsible for managing
componentWillReceiveProps,
shouldComponentUpdate in the life cycle ,
componentWillUpdate,
render and
componentDidUpdate.
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)
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>setState
是React
框架的核心方法之一,下面介绍一下它的原理:
// 更新 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
执行更新。
当状态不为 MOUNTING
或 RECEIVING_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 ); }
如果在
shouldComponentUpdate
或componentWillUpdate
中调用setState
,此时的状态已经从RECEIVING_PROPS -> NULL
,则performUpdateIfNecessary
就会调用updateComponent
进行组件更新,但updateComponent
又会调用shouldComponentUpdate
和componentWillUpdate
,因此造成循环调用,使得浏览器内存占满后崩溃。
开发建议
不建议在 getDefaultProps
、getInitialState
、shouldComponentUpdate
、componentWillUpdate
、render
和 componentWillUnmount
中调用 setState,特别注意:不能在 shouldComponentUpdate
和 componentWillUpdate
中调用 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!

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

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.

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.

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)