What's the difference between declaring methods inside a React class?

7196 views reactjs
11

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 = () => {}

  ...
}

answered question

Can't locate right now, but this is duped multiple times. TL;DR: binding and prototype v instance.

stackoverflow.com/questions/45896230/…, for example (out of votes, sorry).

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

1 Answer

8

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.

posted this

Have an answer?

JD

Please login first before posting an answer.