What is diff algorithm?


When we perform DOM operations, we may need to update a DOM element, but it will not take effect if we do not update the whole component. In fact, we can use diff algorithm with virtual dom.

Virtual DOM

  In essence, it is a JS object to describe what you want to see on the screen

Virtual DOM

Diff algorithm

  Execution process

  When rendering for the first time, react will create a virtual DOM object (tree) according to the initialized state (model)

  Generate the real DOM according to the virtual Dom and render it to the page

  When the data changes (setstate ()), a new virtual DOM object (tree) will be created again according to the new data

  与上一次得到的虚拟DOM对象,使用Diff algorithm比对(找不同),得到需要更新的内容

  Finally, react only patches the changed page tour content into the DOM and re renders it to the page

Diff algorithm

Code demonstration

  After the component render () is called, a virtual DOM object is generated according to the state and JSX structure (the call of the renderwww. Sangpi. Com () method does not mean that the browser renders, but the call of the render method means that the diff algorithm begins to compare)

  In the example, only the text node content of the P element is updated

  First rendered DOM object

Code demonstration

Virtual DOM object after data update

Page tour code demonstration 2


  Working angle: application first, principle second

  The principle is helpful to better understand the operation mechanism of react

  Setstate() asynchronously updates data

  Parent component updates lead to child component updates, and pure components improve performance

  On the premise of clear and simple ideas, virtual Dom and diff ensure efficiency (rendering changed components)

  Virtual DOM - > state + JSX

  The biggest feature of virtual DOM is that it breaks away from the constraints of the browser, which means that react can be used wherever JS can be supported. Therefore, why can react be used for cross platform development

  The above is the introduction of DOM and diff algorithm. I hope it can help you.