cliff-effects icon indicating copy to clipboard operation
cliff-effects copied to clipboard

Remove anonymous functions from event handler props

Open turnerhayes opened this issue 7 years ago • 0 comments

When your render() method passes an anonymous function as a prop, a new function instance will be created and that prop's value will be different every time render() is called, which means that React will assume it needs to refresh the tree, even if nothing has "actually" changed. This can result in unnecessary DOM manipulation.

Wherever possible, we should have the function be a member of the component's class and bind it to this in the constructor, and just pass that function reference.

e.g.

Before:

class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <button onClick={ () => alert(this) } />
      </div>
    );
  }
}

After:

class MyComponent extends React.Component {
  constructor(...args) {
    super(...args);

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    alert(this);
  }

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

turnerhayes avatar Nov 06 '18 23:11 turnerhayes