The time to use bind when working with react components

Hi there,

I’am currently working on the Ravenous Project/Part 3/Task 9


Why do I need to bind this (the current class instance) to the call of handleSortByChange() to not get the Error:

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

On the other hand when I call the getSortByClass() on Task 8, there is no need to bind the function, although both of them are in use of this?

getSortByClass() is setting the name of a class attribute in the HTML so ‘this’ doesn’t really play an important role for defining ‘this’.

handleSortByChange() is setting state so ‘this’ and what “owns” the ‘this’ value becomes important. Specifically SearchBar owns the ‘this’. Man, I know this is confusing stuff. Not sure how else to say it.

You should be able to call the on click handler two different ways and the ‘this’ will get defined correctly:

What happens when you call handleSortByChange() like this using an arrow function? Do you get the same error?

onClick={() => this.handleSortByClass(sortByOptionValue)}

versus this way using .bind()

onClick={() => this.handleSortByClass.bind(this, sortByOptionValue)}

Check out a part of this article about the ‘this’ and the arrow function:

In short, Dave Ceddia says:
" Another type of syntax supported by the class properties feature can make this constructor unnecessary: you can set a property equal to an arrow function, and the arrow function inherits the this binding of the class instance so you don’t have to bind it explicitly. […then he gives an example]"

So if you don’t use an arrow function then you have to bind it explicitly using .bind().

1 Like

Thank you for the explanation and the link, it’s a lot clearer now. And yes, it is quite confusing stuff :slight_smile: