Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-11-06 21:49:02
Original
358 people have browsed it

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')} />
Copy after login

The button will not rerender unless its other props change.

With Inline Arrow Function:

<Button onClick={this.handleClick} />
Copy after login

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} />;
  }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!