Reputation: 1178
So I had a question in one of my interviews today that using arrow functions and bind in render is problematic.
Here's some piece of code:
class Component extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [
{ id: 1, name: "Cory" },
{ id: 2, name: "Meg" },
{ id: 3, name: "Bob" }
]
};
}
deleteUser = id => {
this.setState(prevState => {
return {
users: prevState.users.filter(user => user.id !== id)
};
});
};
render() {
return (
<div>
<h1>Users</h1>
<ul>
{this.state.users.map(user => {
return (
<User
key={user.id}
name={user.name}
id={user.id}
onDeleteClick={() => this.deleteUser(user.id)} // Isn't this okay?
/>
);
})}
</ul>
</div>
);
}
}
How is this line of code onDeleteClick={() => this.deleteUser(user.id)}
problematic? Don't we usually write functions and methods in a similar fashion.
Any help would be appreciated.
Upvotes: 1
Views: 764
Reputation: 314
In most cases, it's perfectly fine. It's important to understand what's happening there: the anonymous arrow function () => this.deleteUser(user.id)
is defined every time that line of code is executed and it uses a bit of RAM.
How expensive is it to define a new anonymous function? It depended on the JavaScript engine but it's usually not much.
Let's extrapolate a little bit: imagine that the users
list had a million entries sick. Most probably that single component would bring the browser to a crawl in any machine. But in this ridiculous scenario, there would be many other places for code optimization to consider first - even design optimizations to avoid getting into this situation - and only after applying the most relevant, then worrying about the specific case of onDeleteClick
since it has such small impact.
Upvotes: 1
Reputation: 800
As pointed out by the @keikai in the documentation it states:
Using an arrow function in render creates a new function each time the component renders, which may break optimizations based on strict identity comparison.
It also states that generally it is ok to use arrow functions in the render method but in cases further optimization required, you should not use arrow functions in the render.
Furthermore, using bind in the render method also creates a new function each time the component renders.
Solution: Bind the function in the constructor(or use an arrow function in the class) and pass it to the prop as a reference and have it called inside the child component appropriately.
Upvotes: 1