Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will using functions to render content hurt react performance?

Tags:

reactjs

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?

like image 266
A.com Avatar asked Oct 22 '25 22:10

A.com


1 Answers

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.

like image 172
Tobias Avatar answered Oct 27 '25 04:10

Tobias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!