Component update mechanism

React mechanism – Component update mechanism

1. Component performance optimization

To reduce the state

  • Reduce state: store only data related to component rendering (e.g. count/ list /loading, etc.)
  • Store only data that changes
  • Minimize the size of state
  • Note: Data not to be rendered should not be placed in state
  • For data that needs to be used in more than one method, put it in this

Avoid unnecessary re-renderingshouldComponentUpdate

  • Component update mechanism: It is clear that parent component updates cause child components to be updated
  • Question: Will subcomponents be re-rendered without any changes, if unnecessary re-rendering is avoided to optimize performance?
  • ShouldComponentUpdate (nextProps, nextState)
  • In this function, nextProps and nextState are the latest states and properties
  • What it does: This function returns true if it needs to be rerendered, false if it does not
  • Trigger time: the hook function in the update phase, executed before the component rerenders (shouldComponentUpdate => render)
//index.js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'

class App extends Component {
    state = { count: 0 }
    handleClick = () = > {
        // Random number when clicking, if this value is different from the last value, then trigger render
        let count = Math.floor(Math.random() * 3)
        this.setState({
            count
        })
        console.log('Click triggered', count);
    }
    shouldComponentUpdate(nextProps, nextState) {
        console.log('nextState'.'Next value' + nextState.count, 'Last value' + this.state.count);
        // If the value does not change, render is not triggered to optimize performance
        returnnextState.count ! = =this.state.count
    }
    render() {
        console.log('Render is triggered');
        return (
            <div>
                <h3>{this.state.count}</h3>
                <button onClick={this.handleClick}>button</button>
            </div>
        )
    }
}
ReactDOM.render(<App />.document.getElementById('root'))

Copy the code

PureComponent pure component

  1. React internal automatically implements a shouldComponentUpdate shallow comparison

  2. PureComponent is the same as react.componentexcept for the first point

  3. Class component use for performance optimization

React.memo Advanced components

  1. Is a higher-order component that receives a component and returns an enhanced component
  2. Enhanced components are not re-rendered when the props are unchanged
  3. Use only function components for performance optimization
//index.js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'

class App extends Component {
    state = { count: 0 }
    handleClick = () = > {
        // Random number when clicking, if this value is different from the last value, then trigger render
        let count = Math.floor(Math.random() * 3)
        this.setState({
            count
        })
        console.log('Click triggered', count);
    }
    render() {
        return (
            <div>
                <CounterR count={this.state.count} />
                <button onClick={this.handleClick}>button</button>
            </div>)}}function Counter(props) {
    console.log('Counter');
    return <h3>Random number case :{props. Count}</h3>
}
// Higher-order components
const CounterR = React.memo(Counter)

ReactDOM.render(<App />.document.getElementById('root'))

Copy the code

2. How do browsers render an HTML document

  1. Browsers parse HTML text files
  2. Parsing the HTML and CSS inside generates a DOM tree and cssOM
  3. The DOM tree and the CSS style tree generate a render tree
  4. Render tree computes layout ==> rearrange
  5. The browser renders according to the render tree ==> redraw

A rearrangement of 1.

  1. What actions will cause the rearrangement
  • The font size
  • Element size change
  • Element position change
  • Element deleted and added
  1. Rearrangement must lead to redrawing

2. Redrawn

Which operations only result in redrawing

  1. Color change
  2. The constant size of the explicit and implicit positions of elements does not affect the size of other elements
  3. Redrawing does not necessarily rearrange
  4. Rearrangements and redraws can cause performance problems

3. How to reduce rearrangement and redrawing

  1. Batch replacement
  2. Local updates update as needed

3. JSX transformation process

  1. jsxThe code will passwebpack babel Plug-in conversion toReact.createElement
  2. React.createElementConverted toJs objectAlso known as the virtual DOM

4. Virtual DOM and Diff algorithm

Virtual DOM

Essentially a JS object that describes what you want to see on the screen

  1. The virtual DOM uses JS to simulate real DOM elements, and js creation is less expensive during our event JS execution because it is in the JS execution environment. However, it would be expensive if we accessed the real DOM elements frequently while executing JS directly.
  2. Therefore, the differences between the old and new virtual DOM are compared through JS. The real DOM can be modified after you get the differences and convert them to the real DOM for better performance.
  3. This modification conforms to the characteristics of local update, batch replacement and on-demand update. High efficiency.

conclusion

  1. Creating JS objects is cheap, so use JS objects to simulate the virtual DOM
  2. The virtual DOM is used to simulate the real DOM
  3. It is more efficient to modify the old real DOM through the differences between the old and the new. Because it causes the least rearrangement and redrawing.
  4. Differences in virtual DOM can be translated not only into DIFFERENCES in HTML, but also into differences in small program tags, mobile App components, embedded components. The maximum effect of the virtual DOM can be developed across platforms. Learn it once and write it anywhere.

The Diff algorithm

Algorithms to speed up the comparison of old and new virtual DOM. If: we have 1000 virtual DOM nodes, then to compare the difference between 1000 old and new virtual DOM will need to compare 1000 * 1000 = 1 million times.

Algorithm principle

React optimizes tree Diff, Component Diff, and Element Diff, respectively.

  1. Tree Diff Compares components at the same layer
  2. Component diff Component type comparison Type inconsistent replace directly
  3. Element diff array elements provide keys to avoid recreations that are simply out of order

1. tree diff

Analysis steps:

  1. The parent node of the top layer is analyzed first. If the parent node is different, all data is considered changed and all replacements are performed
  2. If the parent nodes are the same, they are compared layer by layer until the different parent nodes are found. Then, direct replacement is performed

For those operating across hierarchiesdomReact does not copy the A on the left directly to the D on the rightCreate A create B create C Delete A, B, and CTherefore, try to avoid manipulating DOM elements across hierarchies.

2. component diff

For comparison between components, if D and G are two components with similar structures but different types, React is also considered as different components. Perform direct substitution

3. element diff

For elements at the same level, the old and new elements above are exactly the same except in order. In React, when the algorithm is executed, the element type and KEY are found to be exactly the same. Therefore, only the swap order is executed, avoiding repeated creation and deletion of elements. That’s why we supply a KEY when we loop through an array.

Implementation process

  • When first rendering React creates a virtual DOM object (tree) based on the initialized state (model).
  • The real DOM is generated from the virtual DOM and rendered to the page
  • When data changes (setState()), a new virtual DOM object (tree) is created based on the new data.
  • With the virtual DOM object obtained last time, Diff algorithm is used to compare (find the difference) to get the content to be updated
  • In the end, React simply updates the changed content into the DOM and renders it back to the page
  • What is the virtual DOM: a JS object that represents the styling of dom elements on a page
  • What the virtual DOM does: Update pages efficiently, and react takes the concept of a browser out of the picture
  • How to update the page efficiently: generate an initial virtual DOM tree when rendering the page for the first time, and then regenerate a virtual DOM tree when the data changes, and then compare the old and new DOM trees, and then update the difference
  • The function of the DIFF algorithm is that the old and new virtual DOM trees are compared by the DIFF algorithm
  • How do diff algorithms compare: Tree Diff, Component Diff, Element Diff