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

tpiros picture tpiros  路  3Comments

brendanvinson picture brendanvinson  路  4Comments

weihongyu12 picture weihongyu12  路  3Comments

ryankask picture ryankask  路  3Comments

olalonde picture olalonde  路  3Comments