Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does changing componentDidMount to non-arrow function make hot reloading work again?

For one screen in my React Native app, hot reloading wasn't working. I found that the solution was to change this

componentDidMount = () => {
  <...do stuff with this.props...>
}

to this

componentDidMount() {
  <...do stuff with this.props...>
}

So all I did was change componentDidMount from an arrow function to a non-arrow function. So my question is:

Why does changing it to a non-arrow function make hot reloading work again? I know that making it a non-arrow function means that if the function were called from some other context, the value of this would be re-bound to the context that the function is called in, whereas with an arrow function it will always be bound to the component in which it was defined. But how does this affect hot reloading? Does hot reloading cause componentDidMount to get called from a different context, and this to get re-bound? If so, how would that affect hot reloading?

Thanks!

UPDATE

Some users asked if this were a duplicate of (Methods in ES6 objects: using arrow functions) or (Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?)

This is not a duplicate of either of these. Please note that I did outline the differences between arrow and non-arrow functions. My question is about how these differences apply to hot reloading specifically.

like image 590
gkeenley Avatar asked Nov 06 '22 20:11

gkeenley


1 Answers

I think that when a method is declared as

componentDidMount () {
   <... do stuff with this.props ...>
}

it enables the interpreter to optimize the code because it is a class method - it does not belong to the class itself but it does not change from object to object.

ie there is a class A and method b - in all instances of class A method b will be the same and the optimizer can see it and optimize it

when the method is declared as

componentDidMount = () => {
   <... do stuff with this.props ...>
}

it actually creates a method for each instances A and therefore the optimizer sees different methods b and can not optimize

like image 193
Yaroslav Malyk Avatar answered Nov 14 '22 23:11

Yaroslav Malyk