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.
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.
The previous answers are absolutely correct and are why you would want to be using arrow functions in react classes.
I just wanted to also point out a subtle difference that is a potential pitfall of their use in a class to avoid surprises...
Arrow functions defined on a class are added to the instance as a property that just so happens to be a function, whereas defining not as an arrow function will add the function as a method to the class's prototype.
In React components that will never be extended this is fine, but if the case arises you want to subclass a component, you will not be able to override an arrow function expecting to be able to call the base class via super
, you can only overwrite it in its entirety
class Button extends React.PureComponent {
// class method - overridable in subclass
pressMethod: function(): void {
console.log('beep')
}
// instance property functions - only overwriteable in subclass
pressArrow = (): void => {
console.log('boop')
}
pressArrowTwo = (): void => {
console.log('blip')
}
}
class BigRedButton extends Button {
// class method - overides subclass one,
// can call superclass method via `super`
pressMethod: function(): void {
super.pressMethod() // prints 'beep' to console
console.log('BOOOOOOOOM!!!')
}
// instance property function
// cannot call superclass via `super` as lambda's have no prototype
pressArrow = (): void => {
super.pressArrow() // TypeError - not a function
console.log('BOOOOOOOOM!!!')
}
// completely overwrites instance property of same name in subclass
// doesn't try to access prototype so won't error but is limited
pressArrowTwo = (): void => {
console.log('BOOOOOOOOM')
}
}
The declarations differ in how the function are written and the
context
ofthis
,In the first syntax
the function is written using
Arrow function
syntax.However the second declaration
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
orthis.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 usethis
andthis.setState
with no surprises.Check this answer on why you need to bind functions in React classes