React Performance Detection
Install NPM I react-addons-perf –save and initialize the project with./app/index.js:
// Performance check import Perf from'react-addons-perf'
if(_DEV_){
window.Perf=Perf
}
Copy the code
Before running the React project, open the developer debug panel and type perf.start () in the console to start the test. After doing something on the page, execute perf.end () to stop the test. A list of operations is printed on the console to show the performance results. It is often used in actual project development to check the performance of the project.
If the performance impact is not significant, such as a few seconds to tens of milliseconds per operation, then don’t worry. But if wasting too much time affects their user experience, then we have to fix it.
PureRenderMixin optimization
NPM I react-addons-pure-render-mixin –save
import React,{Component} from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'class Demo extends Component{ constructor(props){ super(props) Enclosing shouldComponentUpdate = PureRenderMixin. ShouldComponentUpdate. Bind (this)} / / omit other code... }Copy the code
The React lifecycle hook has a shouldComponentUpdate. Every time a component changes, we should ask the function whether to update it. If the function returns true, we should update it. If false is returned, the update is not performed. By default, this function always returns true, meaning invalid updates will be executed.
Why are there invalid changes? As we all know, in the React component, changes to the state and props trigger component updates and re-renders. However, in React, sometimes the update will be triggered if the state and props are not changed. This will result in invalid rendering.
Used here enclosing shouldComponentUpdate = PureRenderMixin. ShouldComponentUpdate. Bind (this), is actually a method of component original shouldComponentUpdate rewritten, Check whether props and state have changed before each update, and if so; Return false and true if there is none.
In react development, we try to add PureRenderMixin methods to components to optimize performance.