5

When creating React components I sometimes on the web that methods are created with arrow function syntax, and sometimes without it. E.g.

class Component extends .... {
  someFnk = (param) => { ... }
}

vs

class Component extends .... { someFnk(param) { ... } }

Which approach is better practice? Arrow function makes is safe to use this in function body, however I wonder when in React this could be an issue (when this could change)?

To rephrase the question: when arrow function syntax can safe me from creating a bug?

1 Answer 1

5

As long as you bind class methods in the constructor, the final, overall output is the same.

The following, once compiled operate in an identical manner.

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

  handleBla() {

  }
}

class Foo extends React.Component {

  handleBla = () => {

  }
}

You say "why bind this when in React this won't change". That isn't actually true - all event handlers change the context of this. So make sure to either use the arrow function or bind for event handlers.

Transpiled

Once you transpile both through babel, you can see there is very little difference. The arrow function is simply mapped onto _this (remember this technique from pre-ES6 days?)

var Foo = function () {
  function Foo() {
    _classCallCheck(this, Foo);

    this.handleBla = this.handleBla.bind(this);
  }

  _createClass(Foo, [{
    key: "handleBla",
    value: function handleBla() {
      console.log(this);
    }
  }]);

  return Foo;
}();

var Foo = function Foo() {
  var _this = this;

  _classCallCheck(this, Foo2);

  this.handleBla = function () {
    console.log(_this);
  };
};

Summary:

It's basically the same, but you must use bind context (either via the arrow function or bind) if you intend to use them with events and reference the component. This extremely common as most event handlers refer to state, setState or props, and so you will need the correct this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.