React has the characteristics of extremely fast rendering. This feature depends on React's virtual dom and diff algorithms.
Comparing the two figures, we can find that under the standard dom mechanism, the user's operation on the application directly operates on the real dom. In react, we operate
It is a virtual dom. Data changes or state variables generated by user operations will be saved to the virtual dom.
Calculate the diff algorithm, compare the virtual dom tree before and after the operation, and then synchronize the changed changes to the real dom.
The principle of virtual DOM:
React maintains a virtual DOM tree in memory, and reading or writing this tree is actually performed on the virtual DOM. When the data changes,
React will automatically update the virtual DOM, then compare the new virtual DOM with the old virtual DOM, find the changed part, and get a diff,
Then put the diffs into a queue, and finally update these diffs to the DOM in batches.
Advantages of the virtual DOM: The final modification on the DOM is only the part of the change, which can ensure very efficient rendering.
Virtual DOM: render virtual DOM + diff + update necessary DOM elements
Disadvantages of the virtual DOM: When rendering a large number of DOMs for the first time, due to the addition of a layer of virtual DOM calculations, it will be slower than innerHTML insertion.
DOM Diff algorithm schematic
Under react's diff algorithm, the dom nodes before and after are compared at the same position. As long as they are found to be different, the dom node (including its child nodes) before the operation will be deleted.
, Replaced with the dom node after the operation.
React virtual dom and diff algorithm