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

How to understand that components might do an extra re-rendering when arrow function callback is passed to lower components #3462

Open
qq508852582 opened this issue Dec 24, 2020 · 1 comment

Comments

@qq508852582
Copy link

@qq508852582 qq508852582 commented Dec 24, 2020

Refering to the doc of handling-events

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={() => this.handleClick()}>
        Click me
      </button>
    );
  }
}

The problem with this syntax is that a different callback is created each time the LoggingButton renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.

I got confused
Could anyone provide a demo what shows the difference of the 3 patterns [bind/ public class fields syntax/ arrow function] in rendering

@alexkrolick
Copy link
Collaborator

@alexkrolick alexkrolick commented Dec 24, 2020

If a component is memoized using React.memo() or React.PureComponent, it re-renders when the props change identity. Creating functions inline and passing them as props to such a component means they always get a new function reference, so it will always re-render. Since memoized components are usually wrapped that way because they are expensive to render, this is not ideal.

To get around this problem, you can use React.useCallback() in a hook component or bind the functions (handleClick = () => {...}) to the instance in a class component.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants
You can’t perform that action at this time.