Stop using arrow functions in React
Arrow functions as callback props is silently killing the performance of your React app
by brainsengineering
HTML
<script src="https://fb.me/react-with-addons-15.1.0.js"></script>
<script src="https://fb.me/react-dom-15.1.0.js"></script>
<div id='container'></div>
Babel + JSX
class Root extends React.Component {
state = {
count: 0
};
shouldComponentUpdate(nextProps, nextState) {
return React.addons.shallowCompare(this, nextProps, nextState);
}
componentDidUpdate() {
console.log('ROOT RE-RENDERED');
}
render() {
const {count} = this.state;
return (
<div>
<p>This button has been clicked {count} times</p>
{/* <Button onClicked={() => { this.setState({count: count + 1}); }} /> */}
<Button onClicked={this._handleClicked} />
</div>
);
}
// to re-render, because the prop never changes.
_handleClicked = () => {
this.setState({count: this.state.count + 1});
};
}
class Button extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
return React.addons.shallowCompare(this, nextProps, nextState);
}
componentDidUpdate() {
console.log('BUTTON SHOULD NOT BE RE-RENDERED');
}
render() {
return (
<button onClick={this.props.onClicked}>Click me</button>
);
}
};
ReactDOM.render(
<Root />,
document.getElementById('container')
);