re: React Quick Tip: Use Class Properties and Arrow Functions to Avoid Binding `this` to Methods VIEW POST

re: I prefer to do this: return <button onClick={(() => this.handleClick())}>Click Me!</button>;

Nice! Yes, that certainly works depending on the the use case. This approach works because render() is bound to this of the class by React.

Keep in mind however that you'll have a (rather small) performance hit because the onClick function is being initialized every time render is invoked since that is where it is being defined.


Well, I am not sure if such a thing can be called a "performance hit" since we are talking basically of 1 line of code, and there are plenty of those that run every time the render starts. The complexity of the operation is not even exponential but linear. I don't think that there is any performance concern to worry about in this case.

Enrique, I am afraid there really is a performance hit. Not because you are creating an arrow function on the fly - as you say, that's mostly irrelevant-, but because a new function will be passed as a prop and the component will re-render (needlessly).

If this happens with a button, that's not a problem, but more complex components will noticeably slow down your apps. This is a known caveat, you'll find many references in the web (for example: github.com/yannickcr/eslint-plugin...)

Code of Conduct Report abuse