Home >Web Front-end >JS Tutorial >Why Should You Avoid Using Arrow Functions or Bind in JSX Props?

Why Should You Avoid Using Arrow Functions or Bind in JSX Props?

Susan Sarandon
Susan SarandonOriginal
2024-11-06 21:49:02434browse

Why Should You Avoid Using Arrow Functions or Bind in JSX Props?

Avoid Using Arrow Functions or Bind in JSX Props

Why It's a Bad Practice:

Using arrow functions or bind in JSX props is discouraged as it negatively impacts performance. Here are the reasons:

  • Inefficient Garbage Collection: Creating functions on each render triggers unnecessary garbage collection when the component unmounts.
  • Rerenders Due to Shallow Comparison: PureComponents and components using shallowCompare in shouldComponentUpdate() rerender even if the prop value remains unchanged, since the inline function prop is recreated each time.

Example:

Without Inline Arrow Function:

<Button onClick={() => console.log('clicked')} />

The button will not rerender unless its other props change.

With Inline Arrow Function:

<Button onClick={this.handleClick} />

The button will rerender each time the component renders, even if the handler remains the same.

Best Practice:

To avoid these performance issues, declare arrow functions or bound methods outside of JSX:

class Button extends React.Component {
  handleClick = () => {
    // Handler logic
  };

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

The above is the detailed content of Why Should You Avoid Using Arrow Functions or Bind in JSX Props?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn