Search code examples
javascriptreactjsecmascript-6arrow-functionsclass-fields

When using React Is it preferable to use fat arrow functions or bind functions in constructor?


When creating a React class, which is preferable?

export default class Foo extends React.Component {
  constructor (props) {
    super(props)
    this.doSomething = this.doSomething.bind(this)
  }

  doSomething () { ... }
}

or

export default class Foo extends React.Component {
  doSomething = () => { ... }
}

A coworker of mine thinks that the latter causes memory problems because babel transpiles the code to capture this inside the closure, and that reference will cause the instance to not be cleaned by GC.

any thoughts about this?


Solution

  • The public class field syntax (so doSomething = () => {...}) is not yet part of ECMAScript but it is doing well and I am pretty confident that it will get there.

    So using this syntax forces you to transpile, but it brings advantages:

    • clear, concise syntax for expressing this binding
    • future proof for when browsers support this
    • not concerned with implementation

    For me, this is a clear win. In most cases, you don't even need a constructor(props), saving you from that boilerplate super call.

    If the Babel implementation would cause memory leaks, you can be sure those would have been found and fixed quickly. You are more likely to create leaks yourself by having to write more code.