React has pure components to improve performance and reduce the number of renders. As long as the state and props are the same, there is no need to render again and the result remains the same.

shouldComponentUpdate

In the React documentation, shouldComponentUpdate in the lifecycle function has a special meaning. ShouldComponentUpdate () determines whether the React output is affected by changes to the props or state.

ShouldComponentUpdate () should return true, any changes to props or setState should render the interface again, and return false. Examples are as follows:

//App.js import React from "react" class App extends React.Component { constructor(props){ super(props) this.state = { Name :"gougou"} this.onclick = this.onclick.bind(this)} onclick(){this.setState({name:"} "})} shouldComponentUpdate(nextProps, nextState){ return false; } render(){ return ( <div> hello world <p onClick = {this.onclick}>{this.state.name}</p> </div> ) }Copy the code

In shouldComponentUpdate, we forced it to return false so that we can’t change the contents of the p tag when we click on it.

In React, the only use of this method is for performance optimization. That is, we don’t need to rerender the page when the props and state are not changed. To do this, we need to figure out the logic to implement shouldComponentUpdate, comparing the old and new props and state, but React doesn’t allow us to do that. React itself introduces the concept of PureComponent as pure components.

PureComponent

PureComponent is a built-in component for React. It replaces shouldComponentUpdate with a shallow comparison of props and state.

Shallow comparison refers to the comparison of reference addresses, which can be divided into two categories.

  • Basic data types, which are simply value comparisons 1 == 1 true == true

  • Reference types, such as arrays and objects, are address comparisons, as in the following example:

    class App extends React.PureComponent { constructor(props){ super(props) this.state = { name:[“gougou”] } this.onclick = This.onclick.bind (this)} onclick(){this.state.name[0] = ‘this.onclick.bind ‘; this.setState({ name:this.state.name }) } render(){ return (

    hello world

    {this.state.name}

    )}

In the example above, the name is an array, and the first element in the array is set to “check”, but the reference address is the same as before, so when we click, the component only makes a superficial comparison, and the reference address of name is the same. The content is different, but it does not render the interface.

Once we know the basics of Component and PureComponent, we can avoid unnecessary repetitive rendering.