Nhat
Nhat

Reputation: 409

what is the different between these two functions in react?

I am learning react and in some videos the lecturers use function like this in their component.

function(){} 

and sometimes they use arrow function like this

function=()=>{}

what are the different between these two? whenever I use function(){} I cannot call any props from state so I always use arrow function and it works very well.

Upvotes: 0

Views: 49

Answers (2)

xDreamCoding
xDreamCoding

Reputation: 1694

Arrow function automatically binds this-context to your component. With the normal function you would need to do that yourself in your components constructor like that:

this.func = this.func.bind(this)

Upvotes: 2

patrick
patrick

Reputation: 10273

When using the "fat arrow" function, i.e. myFunc = () => {}, if you try to access this you will receive access to the surrounding function's this. This is because the fat arrow function does not bind it's own this.

When you use myFunc() {} you are binding this and scoping it to that function.

Upvotes: 1

Related Questions