Pure Render Checks
Pure render?
Examples of this are the React.PureComponent, PureRenderMixin, recompose/pure and many others.
Case 1
Bad
You see the options array was passed deep down in the Cell elements. Normally this would not be an issue.
The other Cell elements would not be re-rendered because they can do the cheap shallow equality check and
skip the render entirely but in this case the options prop was null and the default array was used.
As you should know the array literal is the same as new Array() which creates a new array instance.
This completely destroyed every pure render optimization inside the Cell elements.
In Javascript different instances have different identities and thus the shallow equality check always
produces false and tells React to re-render the components.
Good
const defaultval = []; // <--- The fix (defaultProps could also have been used).
class Table extends PureComponent {
render() {
return (
<div>
{this.props.items.map(i =>
<Cell data={i} options={this.props.options || defaultval}/>
</div>
);
}
}
Case 2
BAD
Bad again
class App extends PureComponent {
this.props.update(e.target.value);
}
render() {
return <MyInput onChange={this.update.bind(this)}/>;
}
}
^^In both cases a new function is created with a new identity. Just like with the array literal.
We need to bind the function early
Good
Bad
class Component extends React.Component {
state = {clicked: false};
onClick() {
}
render() {
// Options object created each render if not set
const options = this.props.options || {test: 1};
return <Something
options={options}
// New function created each render
onClick={this.onClick.bind(this)}
// New function & closure created each render
onTouchTap={(event) => this.onClick(event)
/>
}
}
Good
- @esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f"">https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f