Search code examples
reactjsfunctionmethodsvisual-studio-codearrow-functions

Why are Arrow Functions in ReactJS considered as property?


So, I've tried two different approaches as per need, i.e with Arrow Functions and Non-Arrow Functions, and while writing the code I noticed something odd about both of these, the non-arrow function i.e.

  close() {
    this.setState({
      show: false
    });
  }

are considered as method(s) which is true as they are functions, nonArrow

But when I write an Arrow function such as:

  goToNextPage = () => {
    this.setState(({ page }) => ({ page: page + 1 }));
  };

property

It is considered a property, I quite do not understand this behavior. Is this something wrong with VSCode or it is an entirely different thing?


Solution

  • class MyClass { aClassProperty = <whatever_value>; } means that you are creating a new class property for every new instance of the class. The property can be any value you like, but in this case the property is an arrow function, so it's correct.

    aMethod() is shared between every instance of the class, but in React you generally create a new function in the constructor by binding it to this anyway, so the end result is the same.