Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing React Rendering with Function Partial Application

Tags:

reactjs

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...

like image 251
Chet Avatar asked Aug 29 '15 05:08

Chet


1 Answers

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.

like image 112
Alex C Avatar answered Dec 16 '22 04:12

Alex C