SoFunction
Updated on 2025-03-09

A brief discussion on the underlying implementation principle of React

1. Props, state and render function relationship, how do data and pages be linked?

When the state or props of the component change, your render function will be executed again.
Note: When the render of the parent component is executed, the render of the child component will also be re-executeed once (because it is inside the render of the parent component).
That is, when the bound event changes state or props, the render function will re-execute the parsing page. At this time, new data will be used during parsing, so the page will change.

2. Virtual DOM in React

Because the render will be re-rendered as long as the state and props are changed, it can be imagined that the performance requirements for the page to be constantly re-rendered is very high. In fact, the performance of the render is very high, thanks to the virtual DOM.
First, clarify in advance that the relevant operations of DOM require calling web application, which has a relatively high performance loss.

Conventional ideas

  • state data
  • JSX Template
  • Combining data + templates, generate real DOM for display.
  • State change
  • Combining data + templates to generate real DOM and replace the original DOM
    Disadvantages: The first time a complete DOM fragment is generated, and the second time a complete DOM fragment is generated. The second time the DOM replaces the first DOM, so that generation and replacement are very performance-consuming.

Improvement ideas (still using DOM)

  • state data
  • JSX Template
  • Combining data + templates to generate real DOM for display
  • State change
  • Combining data + templates to generate real DOM, and not directly replace the original DOM
  • New DOM (document fragmentation) The original DOM is compared to find the difference (large performance loss)
  • Find out what changes have happened, for example, find out that there are only differences in the input box
  • Only replace the input element in the old DOM with the input element in the new DOM.
    Disadvantages: Performance improvement is not obvious because performance is consumed in comparison.

React's idea

  • state data
  • JSX Template
  • Combining data + templates, a virtual DOM is a JS array object that fully describes the real DOM ([ ‘ idv ‘ , { id : ‘ abc ‘ } , [ ‘ span ‘ , { } , ‘ hello ‘ ] ] ). Using JS to generate JS objects has extremely little performance loss, and generating DOM has a large performance loss, you need to call web application.
  • Use the structure of the virtual DOM to generate the real DOM to display ( < div id=’abc’>< span>hello</ span></ div> ).
  • State changes (< div id=’abc’>< span>bye</ span></ div>)
  • Array + template generates a new virtual DOM ( [ ‘ idv ‘ , { id : ‘ abc ‘ } , [ ‘ span ‘ , { } , ‘ bye ‘ ] ] ) (greatly improves performance)
  • Compare the difference between the original virtual DOM and the new virtual DOM, find the difference is the content in the span (greatly improves performance)
  • Directly operate the DOM to change the content in the span
    Summary: Reduced creation and comparison of real DOM, while creating and contrasting JS objects are created and compared, thus achieving a huge performance leap.

In-depth understanding of virtual DOM

Vue is exactly the same as the principles and steps of virtual DOM in React.
Steps to generate real DOM in React: JSX -> createElement method -> JS object (virtual DOM) -> real DOM.
Therefore, it can be seen that div and other tags in JSX are just the syntax of JSX, not the DOM, and are only used to generate JS objects.
In fact, creating a virtual DOM (JS object) in React is used (without JSX syntax, you can also use the following method to generate it)

// Pass three parameters: tag attribute content// &lt;div&gt;item&lt;/div&gt;
// So in fact, without JSX syntax, you can also use the following method to generate('div',{},'item')

Advantages of virtual DOM:

  • Performance improvement DOM comparison becomes JS comparison
  • It enables cross-platform applications to be implemented, React Native (there is no concept of DOM in Android and iOS, and the use of virtual DOM (JS object) can be used in all applications and then becomes a component of the native client)

3. The diff algorithm of virtual DOM

  • The Diff algorithm is used to compare the difference between the original virtual DOM and the new virtual DOM, that is, how to compare two JS objects.
  • The full name of the diff algorithm is the difference algorithm
  • setState is actually asynchronous, which is to improve the performance of react's underlying performance and to prevent changing state multiple times under short time intervals. In this case, React will merge several changes to state into one time to improve performance.
  • The diff algorithm is a comparison of the same level. Assuming that the two virtual DOM nodes in the first layer are inconsistent, they will not compare downwards. All the virtual DOMs on the original page will be deleted and then replaced with the new virtual DOMs. Although there may be some waste of performance, the performance loss is compensated for because the algorithm compared with the same layer is very high.
  • There is a key value when doing list loops, so that when comparing, you can compare correspondingly, find out what to change and what does not need to be rendered. This uses keys for correlation, which greatly improves the performance of virtual DOM comparison. This requires ensuring that the key value remains unchanged after the new virtual DOM. This shows why the key value should not be index when doing list loops, because there is no way to ensure the consistency of the key values ​​of the original virtual DOM and the new virtual DOM, resulting in performance loss. Generally, this key corresponds to the unique id field of the background data, rather than the loop index.

4. Use of ref in React

  • Use ref in react to manipulate DOM
  • It can also be used in react to get DOM
  • The parameter ref is a function
&lt;input
    id = "insertArea"
    className="input"
    value={}
    onChange={}
    ref={(input)=&gt;{ = input}}
/&gt;

handleInputChange(e){
    // const value = ; // original method    const value = ;
    (() =&gt; ({
        inputValue: value
    }))
}

In general, it is not recommended to use the ref method because setState is an asynchronous function, so when operating the DOM, it may not be able to correctly output the latest DOM situation of the page. Sometimes more complex operations such as animations. If you have to use it, you need to use the second function of setState, which is a callback function, which is triggered when setState is completed.

handleBtnClick(e){
    ((prevState)=&gt;({
        list: [..., ], // Expand operator        inputValue: '',
    }), ()=&gt;{
        (('div').length);
    });
}

5. Lifecycle functions in React

  • A life cycle function refers to a function that the component will automatically call and execute at a certain moment.
  • The render function is an example of a life cycle function. It will be automatically executed when the state or props change.
  • The constructor can be understood as a lifecycle function, which will be executed when the component is created, but it is es6 syntax, not react special syntax.

Component mounting process:

  • componentWillMount is automatically executed when the component is about to be mounted to the page, and is executed before rendering
  • It must exist for render to mount
  • componentDidMount is executed after the component is mounted to the page.
  • Note: When state and props are changed, only render will execute, componentWillMount and componentDidMount will not execute, they will only be executed when they are mounted to the page for the first time.
  • Component update:
  • componentWillReceiveProps Both conditions must be met: 1. When a component receives parameters from the parent component 2. If this component exists in the parent component for the first time, it will not be executed, and if this component has existed in the parent component before, it will not be executed.
  • ShouldComponentUpdate component will be executed before it is about to be updated. For example, when the focus input box is used, it will return a true and false to determine whether to update.
  • componentWillUpdate will be automatically executed before the component update is updated, and will not be executed after the shouldComponent returns true.
  • componentDidUpdate is executed after the component update is completed.
  • Component removal process:
  • componentWillUnmount: But this component is about to be removed from the page when it is executed.

6. Use scenarios of life cycle functions

  • Prevent the child components from rendering when rendering the parent component, so as to improve performance.
  • shouldComponentUpdate(nextProps,nextState){if( !== ){return true} return false}
  • When the page is initialized, send AJAX request in componentDidMount (recommended), or in the constructor, do not put it in the render, as it will cause a dead loop, and it is also best not to send ajax in componentWillMount. There is no problem with putting it in this, but there will be problems in react native.
  • react does not have ajax built-in, use axios.

This is the end of this article about the principle of the underlying React implementation. For more related underlying React content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!