We should avoid method binding inside render because during re-rendering it will create the new methods instead of using the old one, that will affect the performance.
How to avoid this way of binding inside render method or what are the alternatives of this?
If you care about re-rendering then shouldComponentUpdate
and PureComponent
are your friends and they will help you optimize rendering.
You have to extract "Child" component from the "Parent" and pass always the same props and implement shouldComponentUpdate
or use PureComponent
. What we want is a case when we remove a child, other children shouldn't be re-rendered.
Example
import React, { Component, PureComponent } from 'react';
import { render } from 'react-dom';
class Product extends PureComponent {
render() {
const { id, name, onDelete } = this.props;
console.log(` render()`);
return (
-
{id} - {name}
);
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
products: [
{ id: 1, name: 'Foo' },
{ id: 2, name: 'Bar' },
],
};
this.handleDelete = this.handleDelete.bind(this);
}
handleDelete(productId) {
this.setState(prevState => ({
products: prevState.products.filter(product => product.id !== productId),
}));
}
render() {
console.log(` render()`);
return (
Products
{
this.state.products.map(product => (
))
}
);
}
}
render( , document.getElementById('root'));
Demo: https://codesandbox.io/s/99nZGlyZ
Expected behaviour
render()
When we remove
is re-rendered.
To see those messages in demo, open the dev tools console.
The same technique is used and described in article: React is Slow, React is Fast: Optimizing React Apps in Practice by François Zaninotto.