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

2k views Asked by At

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?

3

There are 3 answers

2
w00t On BEST ANSWER

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.

0
v kay On

The link here clearly highlights that officially it's safe to "Bind methods in constructor" rather than using the arrow function as a short code to achieve event binding.

Here is the link: https://reactjs.org/docs/react-without-es6.html#autobinding for reference.