Reputation: 718
I've read that it's good practice to declare function as component's method instead of inlining it in render
, because every time parent component is rendered it creates new function and messes up with child's shouldComponentUpdate
.
I.e. this:
<button onClick={this.handleClick} />
is better than that: <button onClick={e => someAction(e)} />
But what about curried functions? Is the following considered as creating new function?
class Parent extends Component {
handleClick = data => event => someAction(data);
render() {
const data = 123;
return <button onClick={this.handleClick(data)} />;
}
}
I know that the "performance impact" may be unnoticable there, but I find partially applicating function paramaters while passing down the component tree very convienent and I'm wondering if it's against best practices.
Upvotes: 6
Views: 1423
Reputation: 4330
Yes it has negative performance impact because of the extra function invocation. But do you really have to worry about it? Most likely not. There are popular React patterns that use closures in render
, like https://reactjs.org/docs/render-props.html Measure first to avoid spending energy on imaginary performance bottlenecks.
Upvotes: 6
Reputation: 36209
Yes. Every time you execute handleClick
you will get in return a new function. In other words purpose of handleClick
is to return a new function. If you remove some of the implicit syntaxes you will get:
handleClick = data => {
const innerFunction = event => someAction(data);
return innerFunction;
}
Side note: I've read some benchmarks that such performance impact by creating functions in render may have less impact than most people think.
Upvotes: 3