What’s the use of PureComponent?

ShouldComponentUpdate should return true by default, but if the parent component doesn’t change its props or props, it should render the child component. This should be done if the child component inherits PureComponent.

The rationale for PureComponent

  1. Override shouldComponentUpdate method.
  2. Make a shallow comparison of the data in the new/old state and props of the component, returning false if there is no change and true if there is no change.

PureComponent usage instance

import React, { Component,PureComponent } from 'react'
import ReactDOM from 'react-dom'


class App extends Component {
    state = {
        m1: 1
    }
    
    test1 = () = > {
        this.setState(state= > ({
            m1: state.m1 + 1
        }))
        // this.setState({})
    }
    render() {
        console.log('call A render:');
        return (
            <div>
                <h1>M1 ={this.state.m1}</h1>
                <button onClick={this.test1}>A test of 1</button>
                <B m1={this.state.m1}/>
            </div>)}}class B extends PureComponent {
    state = {
        m2: 1
    }
    
    test2 = () = > {
        this.setState({})
    }
    render() {
        console.log(Call B render:);
        return (
            <div>
                <h1>M2 ={this.state.m2}, m1={this.props. M1}</h1>
                <button onClick={this.test2}>Test 2 B</button>
            </div>
        )
    }
}

ReactDOM.render(<App />.document.querySelector('#root'));
Copy the code

CodeSandBox online demo