0


I know that there are already some threads about that, but I was not able to find an actual one. So my question is, should I always use the bind approach or the arrow functions? What are the pros/cons of them in 2020? From what I read I know, that (at least in 2018) the bind methods had a better performance. Another question: Should I just bind the functions, which I call use in the render method via a click? Here a small example

constructor(super) {
props(super)

this.firstBind = this.firstBind.bind(this);
this.secondBind = this.secondBind.bind(this;
}

render() {
return (
<Button title="First Bind" onClick={this.firstBind} />
<Button title="First arrow" onClick={this.firstArrow} />
)
}

firstArrow = () => {
//some outout
}

secondArrow = async() => {
//fetch some data from a database and output it
}
secondBind() {
//some output
}
async secondBind() {
//fetch some data from a database and output it
}

My goal is to understand it completely.
Thanks a lot!
Jan

Sylber
  • 961
  • 1
  • 7
  • 15
  • Does this answer your question? [Binding vs arrow-function (JavaScript or react onClick)](https://stackoverflow.com/questions/50375440/binding-vs-arrow-function-javascript-or-react-onclick) – Top-Master Jul 23 '21 at 17:11

1 Answers1

4

You are right, this question has been asked many times before and it will likely be closed because it has so many duplicates, but I will provide a short answer anyways.

Bind and arrow functions achieve the same in a React component

On a more technical level binded functions and arrow functions are different, but for the react world which you are talking about, they are the same, the simply create a function which is bound to the context of the instance that created them, so you can access the instance variables when they execute.

But why then is there two ways to create binded functions?

Why then, would you ask, go through the trouble of having two ways of creating context-binded functions? well, even though they achieve the same you can tell that that the .bind version is more verbose and also prone to error, as you might forget to bind the functions on the constructor, therefore it is considered good practice to use arrow functions.

The react team did not create them, they are a part of javascript and having to bind functions is just a consequence of the underlaying design of the language, React only forces you to bend javascript to properly work as an OOP language.

Ok, so what should you do?

That being said, the react ecosystem is moving towards hooks, and even though the team responsible for react keep repeating one does not need to use hooks, the tendency is clear, class components will disappear, ex: as libraries update to use hooks and maintaining to different ways of accessing them is too much trouble, most of them use hooks only.

So TL:DR in 2020: this question is no longer relevant, go use functional components with hooks and you will have no problems

Oscar Franco
  • 5,691
  • 5
  • 34
  • 56