Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove anonymous functions from event handler props #974

Open
turnerhayes opened this issue Nov 6, 2018 · 0 comments
Open

Remove anonymous functions from event handler props #974

turnerhayes opened this issue Nov 6, 2018 · 0 comments
Labels
tech-debt Used for issues that typically don't directly affect what the end user sees, such as coding styles

Comments

@turnerhayes
Copy link
Collaborator

turnerhayes commented Nov 6, 2018

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 turnerhayes added the tech-debt Used for issues that typically don't directly affect what the end user sees, such as coding styles label Nov 6, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
tech-debt Used for issues that typically don't directly affect what the end user sees, such as coding styles
Projects
None yet
Development

No branches or pull requests

1 participant