current position:Home>When to use react PureComponent

When to use react PureComponent

2022-04-29 04:25:59baoleilei6

If you used React, So you are right React. component Familiar with . It may be what you want to extend every time you create a new stateful component .App.js Is a class component that does this :

import React from 'react';
export default class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      message: 'hello',
    };
  }
  render() {
    return (
      <main>
        {this.state.message}
      </main>
    );
  }
}

But there is another less well-known component class , It can be extended to React.PureComponent. What's the difference between these two classes ? Why use PureComponent.

React.PureComponent It is mainly used to improve performance

The following is an excerpt from the official documents :

If your React component’s render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.

What exactly does this mean ? Suppose we have a subcomponent child.js :

import React from 'react';
const Child = props => <div>{ props.message }</div>;
export default Child;

This component receives... From its parent component props. We want this component to re render when it receives new props . But what if its parent process tracks different types of States ? Even if the item received by the sub component has not changed , Whether the parent component will trigger the re rendering of the child component .

Suppose the parent component is like this :

import React from 'react';
import Child from './Child';
export default class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0,
      message: 'hello',
    };
  }
  render() {
    return (
      <main>
        {this.state.counter}
        <br />
        <Child message={this.state.message} />
      </main>
    );
  }
}

Parent.js Rendering <main> Element requires two sets of elements ,counter and message.message The state is through Child Component rendered .

Take a closer look at the state in the constructor method , The parent method tracks our state here :

this.state = {
  counter: 0,
  message: 'hello'
};

Given these components , If we run yarn start, We'll get this result in the viewport :

0
hello

0 Render from parent component ,hello Render from subcomponents .

Now there is counter and message these two items. state, Can pass props Pass to subcomponent . Observe again Child.js, Will find Child Only receive messgae. If counter Discover change , We didn't want Child.js To render , because Child Not used counter. For such a small project , Re rendering at this level may not make much difference , But unnecessarily re rendering piles and piles of subcomponents can hinder the performance of larger projects .

When our sub components are re rendered , We can do something to test . By placing... In each component console.log() sentence , We can check which statements are re rendered after a particular event .

Let's test with parent and child components . First , Let's add a to the parent component console.log(). Let's also provide a way to change our counter state :

import React from 'react';
import Child from './Child';
export default class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0,
      message: 'hello',
    };
  }
  handleClick = () => {
    this.setState(prevState => ({ counter: prevState.counter + 1 }));
  };
  render() {
    console.log('parent rendered');
    return (
      <main>
        {this.state.counter}
        <br />
        <Child message={this.state.message} />
        <button type='button' onClick={this.handleClick}>Increment</button>
      </main>
    );
  }
}

We give <button> Added a handleClick() Method . such , We can add counter state , This will trigger the re rendering of the parent component .

If we click the button several times and check the console , We will see every time counter When the state increases, the parent component will be re rendered .

therefore , We add console.log Statement in the subcomponent and check whether it is based on counter The value of is automatically re rendered every time it changes :

import React from 'react';
export default class Child extends React.Component {
  render() {
    console.log('child rendered');
    return (
      <div>{ this.props.message }</div>
    );
  }
}

I convert the subcomponent into a class component , Just to add one console.log() sentence . In the real world , This is not a good reason to use this component as a class . For all that , Although there are console.log() sentence , The subcomponents in this version are basically the same as stateless components .

What does this reflect ?

Component and PureComponent The biggest difference between them is PureComponent Automatically implemented shouldComponentUpdate() Life cycle approach .

And about shouldComponentUpdate The expression of is like this :

Use shouldComponentUpdate() Give Way React Know whether the output of the component is not affected by the current state or props The impact of changes in . The default behavior is to re render each time the state changes , In the vast majority of cases , You should rely on the default behavior .

As we know console.log() As the experiment shows , The default behavior of a component is to re render each time the state changes .shouldComponentUpdate() A previous checkpoint is automatically re rendered , Used to evaluate whether a change in state is related to its associated component .

Yes , You can do this manually shouldComponentUpdate(), however PureComponent Will do this implicitly , And sometimes it's just what you want . You can see , Switch dozens of stateful subcomponents to extension PureComponent Can prevent a lot of unnecessary re presentation .

Should we use as much as possible Pure.Component

Sometimes , Use PureComponent It doesn't make much sense , Even if it does help optimize performance . In the example above , Besides using console.log() outside , In fact, there is no need to Child Become a stateful class component . If there's no reason to think it's a class , Then it will neither expand Component It will not expand PureComponent, And convert it into a class just to use PureComponent There is no need to .

however , If the subcomponent is a class , And only some props passed to their parent components , that PureComponent It may be worth studying .

Translator's summary

Recently, it has been observed that many components are used Pure.Component Usage of , The feeling after reading this article is :

  • PureComponent The purpose of is to optimize performance , So how to reflect , By not being affected by the parent component state The changed sub components are not rendered .
  • principle : adopt shouldComponentUpdate Check the monitoring mode of , Specifically, you can see the relevant articles of this hook function .
  • PureComponent Another concept that comes to mind is stateless components , Is that you don't have state, All the rendered data comes from props To obtain the , Can be rewritten as PureComponent The way .

copyright notice
author[baoleilei6],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/117/202204270552176530.html

Random recommended