React, ineffiencies of binding a new function for each event

一曲冷凌霜 提交于 2019-12-06 08:12:33

I'm not sure this is a good idea, but... memoize!

class Foo {
  constructor(){
    this.getClickHandler = _.memoize(this.getClickHandler);
  }

  getClickHandler(index){
    return (event) => {
      doSomething();
    };
  }

  render(){
    // ...
       <button onClick={this.getClickHandler(index)}>Click me</button>
    // ...
  }
}

This way you avoid creating a new function, avoid data-attributes, and avoid the performance cost of looking up anything in the dom.


I don't think I've ever profiled and found creating functions in render to be an issue. This is definitely something you should optimize only when the numbers tell you to do so.

I think in general binding functions directly in render is the idiomatic way because they do it in the docs as you pointed out and in our experience has not been significantly less performant. However, there are cases you don't want to rebind the function on every render, for example if you're comparing props in shouldComponentUpdate (like with PureRenderMixin). To do something very similar as your friend suggests but without looking at the DOM with jQuery (and I believe is a common pattern) you can pass the index as a prop.

class Parent extends React.Component {
  render() {
    return [...some array].map((item, index) => {
      return <Child item={item} index={index} />;
    });
  }
}

class Child extends React.Component {
  constructor() {
    super();
    this.handleClickButton = this.handleClickButton.bind(this);
  }

  handleClickButton() {
    // use this.props.index here
  }

  render() {
    return <button onClick={this.handleClickButton}></button>;
  }
}

Note when using ES6 classes you need to bind to this manually in constructor since you're accessing this.props. You don't need to if you're using React.createClass. More about ES6 classes in React docs here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!