current position:Home>When to use react PureComponent
When to use react PureComponent
2022-04-29 04:25:59【baoleilei6】
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
The sidebar is recommended
- Basic usage of JavaScript
- About the problems encountered in the value transfer of react parent-child components! (Language JavaScript)
- How to realize the function of jQuery small ticket printing
- [JavaScript] handwriting a lazy loading component
- HTTP protocol
- JavaScript performance optimization
- I've taught myself Python for half a month. I feel it's useless. What should I do?
- Is it a blessing or a curse that the biggest customer of Ningde era changes ownership of Tesla?
- Element UI realizes the function of table radio selection
- Elementui realizes the function of table radio selection
guess what you like
Apache shardingsphere code formatting practice -- spotless
Vue console error information collection and reporting
Initialize the react project environment under mac
React dynamically adds elements to the list
React realizes form data collection
Vernacular react life cycle
JavaScript generates a tree
vue2. How to register and login with 0 + koa2 + mongodb
vue. JS how to realize single page application
How to realize login registration and token verification in Vue
Random recommended
- How to set the background color for individual pages in Vue cli
- How does Vue router cooperate with elementui to realize navigation
- Vue2 how to load more data on the scroll bar
- How to use margin and padding in CSS
- How does vue2x implement the vueslidershow function of the responsive adaptive rotation component plug-in
- How does vue2 recursive component implement tree menu
- How to use the three selectors of CSS
- Same blog, different styles -- hexo alternative construction
- Optimize nginx HTTPS latency - see how I can speed up nginx by 30%?
- The development model in the era of consumer Internet only transfers industrial elements from offline to online
- Advanced features of Vue
- CSS shadow advanced, to achieve a more three-dimensional shadow effect!
- Introduction to the number type method in JavaScript
- Differences between nginx forward and reverse proxy
- Front end schema form configuration generation scheme
- Units that can be used by the rotate method of transform in CSS
- Why CSS3 sticky doesn't work?
- [bug resolution] webpack error: module not found Did you mean xxx
- [bug resolution] can't perform a react state update on an unmounted component This is > a no-op, but it...
- Remember to speed up the construction of a webpack
- Browser review hover element
- Vue insert iframe
- Vue realizes downloading pictures
- Some common problem-solving methods in Vue (sort out some truly effective methods that can be used in the project) (wait for continuous update and accumulation)
- About database data response to HTML page, Chinese appears? Solution to garbled code (multiple question marks)
- Ask a question about CSS selector
- When Vue jumps the route, the timer cannot be cleared in time
- Document is not defined
- Vue quill editor stepping on pit record -- the echo style of rich text content is wrong
- The multi selection box of table in element is combined with paging to echo the bug step hole
- Vue project optimizes the loading speed of the first screen
- Use / deep / to report an error CSS (CSS selected expected)
- Nginx configuration
- Vue cli reverse proxy
- Vuex persistedstate plug-in - vuex persistent storage
- Understanding and summary of CSS
- vue2. Implementation of X data response
- JavaScript content understanding
- Props in react
- JavaScript stack“