Reputation: 1645
This article (and other places) mention now calling functions inside of render:
https://levelup.gitconnected.com/optimize-react-performance-c1a491ed9c36?ref=reddit
I've always used a pattern for large React class components where I'll move some of the JSX out of the render function into methods. This avoids having a billion little one-time-use separate components and it also avoids having to put lengthy if/then or ternary logic inside of a render area which I find slightly harder to read.
class HelpModal extends React.Component {
state = { visible: false };
renderContent = () => {
if (this) {
return <div />
}
if (that) {
return <span />
}
}
render() {
return (
<Modal visible={this.state.visible}>
{this.renderContent()}
</Modal>
);
}
}
I've seen this strategy in a bunch of places, but now it sounds like, based on the above blog post, that this may be a bad practice performance-wise?
Upvotes: 4
Views: 2050
Reputation: 954
It depends on how you use inline functions.
React calls the render function after props and/or state changes. Each time they change the render function is called.
If you compute things that haven't changed because of the new props/state values then this inline function has indeed a negative impact on your app's performance.
Example:
render() {
<div>
{ this.props.items.map(() => <SomeComponent />) }
</div>
}
If you compute it here or anywhere else doesn't change the fact that you need to compute it each time the render function is called. No negative effect at all.
computeStaticStuff(x, y) {
return x + y > 0 ? <p /> : <i />;
}
render() {
<div>
{ () => this.computeStaticStuff(5, 6) }
</div>
}
This would be a ((n) extremely stupid) example of recomputation that is not needed at all.
Upvotes: 4