Javascript: Suggestion for React Methods - binding event handlers

Created on 21 Sep 2016  路  2Comments  路  Source: airbnb/javascript

While I do agree with binding event handlers in the constructor, I've seen a huge trend in creating arrow functions and assigning them to a variable like

onClickDiv = () => {
  // Do stuff
}

By doing this, there is no need for having to bind this. I was wondering whether this would make for a cleaner, less error-prone convention? Thoughts?

question react

All 2 comments

This is a very bad idea. This creates one function-valued instance property per instance - as opposed to one optimized function on the prototype that's simply bound per instance.

In other words, both approaches have per-instance properties, but only the latter will have a single, shared, optimized function that's accessible on the prototype.

Separately, this syntax is "public fields", which is a stage 2 proposal - in other words, it's not part of JavaScript yet, and this guide does not permit/encourage things to be used before stage 4 (stage 3 on a case-by-case basis).

@ljharb thanks a lot for the detailed explanation!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JacksonGariety picture JacksonGariety  路  43Comments

josmardias picture josmardias  路  37Comments

molily picture molily  路  37Comments

SimenB picture SimenB  路  34Comments

MartialSeron picture MartialSeron  路  153Comments