Home > Article > Web Front-end > What is react's diff method?
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.
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.
The minimum number of to convert a Virtual DOM tree into an Actual DOM tree The process of operation is called reconciliation.
diff algorithm is the specific implementation of reconciliation.
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. (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. 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. 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 . Notice: As shown in the figure above, When component D changes to component G, even if the two components have similar structures, ##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. situation 1: How to move the node when the same node exists in the old and new sets but in different positions
(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: Based on tree diff: Based on component diff: Based on element diff: Recommended learning: "react video tutorial"
4. Tree diff:
##5. component diff :
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
_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
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!