Home >Web Front-end >JS Tutorial >Why Should You Avoid Binding or Inline Arrow Functions in React's Render Method?
Avoiding Bind or Inline Arrow Functions in Render Method
Introduction
Binding functions or using inline arrow functions within the render method is discouraged in React because it can create performance issues during rendering. This article explores alternatives to this practice and provides examples of their implementation.
Issues with Binding in Render
When binding functions or using inline arrow functions in render, a new instance of the function is created with each rendering cycle. This can lead to performance degradation, especially in cases of frequent re-rendering.
Alternatives to Binding
Using Component Constructor:
Using Property Initializer Syntax:
Scenario: Passing Extra Parameters
Consider the case of passing extra parameters to event handlers within a map function. For example, consider deleting an item from a todo list:
todos.map(el => <div key={el} onClick={this._deleteTodo.bind(this, el)}> {el} </div>)
Solution: Child Component
To avoid binding, create a child component for the mapped content:
Parent Component:
deleteTodo = (val) => { console.log(val) } todos.map(el => <MyComponent val={el} onClick={this.deleteTodo}/> )
Child Component (MyComponent):
class MyComponent extends React.Component { deleteTodo = () => { this.props.onClick(this.props.val); } render() { return <div onClick={this.deleteTodo}> {this.props.val} </div> } }
In this approach, the event handler function resides in a child component, delivering better performance during rendering.
Example:
Here is a complete example demonstrating the child component approach:
class Parent extends React.Component { _deleteTodo = (val) => { console.log(val) } render() { var todos = ['a', 'b', 'c']; return ( <div>{todos.map(el => <MyComponent key={el} val={el} onClick={this._deleteTodo}/> )}</div> ) } } class MyComponent extends React.Component { _deleteTodo = () => { console.log('here'); this.props.onClick(this.props.val); } render() { return <div onClick={this._deleteTodo}> {this.props.val} </div> } } ReactDOM.render(<Parent/>, document.getElementById('app'));
The above is the detailed content of Why Should You Avoid Binding or Inline Arrow Functions in React's Render Method?. For more information, please follow other related articles on the PHP Chinese website!