React Series: component performance optimization (shouldComponentUpdate, PureComponent, PureRender, Immutable)

Sometimes there will react in the render unnecessary, for example: a parent component subassembly to pass props, props is not updated even if the subassembly will again render; 2 setState twice the same value, will render..

Optimization

1. shouldComponentUpdate

shouldComponentUpdate accepts two parameters, and to update the State props, returns true or false to determine whether to execute the render;

So by comparing the old and new values ​​are the same values, the same returns false, different to optimize returns true

class MyComponent extends React.Component {
	constructor(props) {
		super(props)
		this.state = {
			searchMore: false
		}
	}
	shouldComponentUpdate(nextProps, nextState){
		if(nextState.searchMore !== this.state.searchMore){
			return true
		}
		return false
	}
}

2. Use react in PureComponent

For stateless components, we can inherit PureComponent at the time of creation, so props when there is no change, it will not re-render the

class MyComponent extends React.PureComponent {
	constructor(props) {
		super(props)
	}
	render(){
		return(
			<div>{this.props.text}</div>
		)
	}
}

3. Use decorator pureRender

The principle of the method with the same 1 to determine whether it is necessary to re-render life-cycle approach by strengthening shouldComponentUpdate
Note: This method can only be relatively shallow

npm install

npm i pure-render-decorator

use

import pureRender from 'pure-render-decorator';

@pureRender 
class MyComponent extends React.Component {
	constructor(props) {
		super(props)
	}
	render(){
		return(
			<div>{this.props.text}</div>
		)
	}
}

Immutable.js achieve deep target performance optimization

Several methods can only props and state were relatively shallow, if relatively deep, then you can, but more consumption performance, contrary to the original intention

Immutable data is immutable once created out of it, you can achieve advanced storage and change detected by simple logic. Data are updated every time a new update data

Immutable.js offers many permanent immutable data structures, including: List, Stack, Map, OrderedMap, Set, OrderedSet and Record.

installation

npm install immutable

use

var map1 = Immutable.Map({ a: 1, b: 2, c: 3 });
var map2 = map1.set('b', 50);
map1.get('b'); // 2
map2.get('b'); // 50
Published 66 original articles · won praise 13 · views 60000 +

Guess you like

Origin blog.csdn.net/haoyanyu_/article/details/100990618