Hacker News new | ask | show | jobs
by martin-adams 3137 days ago
My understanding is that arrow functions aren’t used as part of a class definition, but for things like anonymous functions in callbacks, preserving the ‘this’ context when something else is invoking it.

E.g. el.onClick((e) => {this.doSomething();});

In that case something else will invoke the onClick callback but we want the ‘this’ context to the same as when we set up the onClick.

2 comments

That's why I mentioned it since it seems to be something like 90% of the bugs I've seen related to this. It's not a coincidence that this is the example used in the article.
Disadvantage is that creating a new function on every render ruins performance optimizations like `React.PureComponent`. Although that's a pretty minor detail, (you shouldn't prematurely optimize, and sometimes PureComponent is actually more expensive than rerendering since computing whether props have changed can be more expensive than just rerendering.)