Search code examples
javascriptreactjsarrow-functionsecmascript-nextclass-fields

What's difference between two ways of defining method on React Class in ES6


I see this a lot in ES6 React code

class Foo extends React.Component {
  bar = () => {
    console.log("bar")
  }

  baz() {
    console.log("baz")
  }
}

Seems like they both define methods bar and baz on Foo but how are they different.


Solution

  • The declarations differ in how the function are written and the context of this,

    In the first syntax

    bar = () => {
        console.log("bar")
      }
    

    the function is written using Arrow function syntax.

    An arrow function does not have its own this; the this value of the enclosing execution context is used. Hence this keyword inside this function will refer to the context of the React class

    However the second declaration

    baz() {
        console.log("baz") 
    }
    

    is a simple function and this keyword in this function refers to the context of the function itself.

    So when you try to access React class Properties/functions like this.state or this.setState you will get an error in the second case(if you haven't used binding anywhere else for this function(example constructor)) whereas it would work in the first case since for an arrow function, this means the same thing within the function body as it does outside of it. Which means that if you use arrow functions within your component’s custom functions, they can use this and this.setState with no surprises.

    Check this answer on why you need to bind functions in React classes