So I was coding an app with React and I noticed that one component have a lot of function.bind(this)
. Is this a good practice?
Asked
Active
Viewed 47 times
0

Saul Chavez Sanchez
- 45
- 5
-
2this is mostly a matter of opinion. Me, I find it an incredibly dumb idea to advocate for this, because your constructor should never need to specify what other functions exist in the class - that's literally what the class itself is already for. So instead you can just use `onClick={evt => this.handleClick(evt)}` and things work, _and_ you'll never notice a performance difference, while your code has a lower bug surface. However, that's just an _opinion_ and you're going to have to form your own. – Mike 'Pomax' Kamermans May 01 '20 at 22:33
-
1Use arrow functions and you won't have to bind anything. – JMadelaine May 01 '20 at 22:48
-
Alternatives can be found here: [React: "this" is undefined inside a component function](https://stackoverflow.com/questions/33973648/react-this-is-undefined-inside-a-component-function) – Emile Bergeron May 01 '20 at 22:54
-
Take a look at this [article](https://medium.com/@charpeni/arrow-functions-in-class-properties-might-not-be-as-great-as-we-think-3b3551c440b1) that explains the differences between using arrow functions vs functions in class components – Mauricio Avendaño May 01 '20 at 23:42
1 Answers
0
You have only two ways for saving context: .bind() and arrow function.
I had some research what the way is better, but both have advantages and disadvantages. I transpiled ES6 class through Babel and the result was interesting
The arrow function is located in the constructor and creating the function (method) each time when you trying to create an instance of the class.
In the case of bind. The method is located in prototype and is not creating for each instance of the class, but when you bind the function it's creating new instance of prototype function.
I think the difference is pretty small between solutions. If you want more proves with code and you want to understand why arrow function doesn't lose context -> link

IT's Bruise
- 824
- 5
- 11
-
The arrow function located in the constructor means for each instance of the class we are creating a new function so if you have too many components that could lead to a performance issues. – Mauricio Avendaño May 01 '20 at 23:50
-
@MauricioAvendaño On my opinion, .bind little bit leading way by performance. But in each component you do this string `this.doSomething = this.something.bind(this)` it's not much better than just create new function. The difference too small and facebook team used to use arrow function and don't care about it (now the use react hooks, useCallback) – IT's Bruise May 02 '20 at 08:19