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 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
; thethis
value of the enclosing executioncontext
is used. Hencethis
keyword inside this function will refer to the context of theReact 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With