-1

What's the difference (if any) between the 2 below ways of defining a method inside a React component?

export default class Foo extends React.Component<
  bar() {
    ...
  }

  bar = () => {}

  ...
}
stackjlei
  • 9,485
  • 18
  • 65
  • 113
  • Can't locate right now, but this is duped multiple times. TL;DR: binding and prototype v instance. – Dave Newton Jul 13 '20 at 20:48
  • https://stackoverflow.com/questions/45896230/arrow-vs-classic-method-in-es6-class, for example (out of votes, sorry). – jonrsharpe Jul 13 '20 at 20:48
  • See https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable – Daly Jul 13 '20 at 20:48
  • Does this answer your question? [Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable) – Daly Jul 13 '20 at 20:48
  • The arrow function declaration doesn't keep "this" instance of the class, in class based components is most common to use regular declarated functions and in function based components it's way more common to use arrow functions – HYAR7E Jul 13 '20 at 20:51

1 Answers1

-1

This isn't really a React-specific question and more about classes in JavaScript.

The first one is a method, the second is a property to which an arrow function is assigned. The practical difference is that the second one will be bound to the object (i.e. this) and the first one will not.

In React this is typically used if the function will be passed to another function or component as a callback.

Alan Plum
  • 10,814
  • 4
  • 40
  • 57