codeforboston / cliff-effects

Cliff effects guidance prototype (archived)
https://codeforboston.github.io/cliff-effects/#/
MIT License
30 stars 64 forks source link

Remove anonymous functions from event handler props #974

Open turnerhayes opened 5 years ago

turnerhayes commented 5 years ago

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>
    );
  }
}