React components compare props with object reference equality, and when you partially apply a function, you get a new function with a different reference which causes a react component to trigger a re-render every single time.
Has anyone faced this issue?
I have a function that renders a component in a specific tab. And one of the props is this.setTab.bind(this, tab)
which returns a new function every single time. It would be really cool if there was some kind of immutability helper which allows this to be equal based on the bound value...
I'm pulling this directly from the eslint plugin docs "jsx-no-bind", and it mentions one possible solution to reduce the number:
A common use case of bind in render is when rendering a list, to have a seperate callback per list item:
var List = React.createClass({
render() {
return (
<ul>
{this.props.items.map(item =>
<li key={item.id} onClick={this.props.onItemClick.bind(null, item.id)}>
...
</li>
)}
</ul>
);
}
});
Rather than doing it this way, pull the repeated section into its own component:
var List = React.createClass({
render() {
return (
<ul>
{this.props.items.map(item =>
<ListItem key={item.id} item={item} onItemClick={this.props.onItemClick} />
)}
</ul>
);
}
});
var ListItem = React.createClass({
render() {
return (
<li onClick={this._onClick}>
...
</li>
);
},
_onClick() {
this.props.onItemClick(this.props.item.id);
}
});
This will speed up rendering, as it avoids the need to create new functions (through bind calls) on every render.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With