I understand you might feel this is a redundant question but hear me out.
I am working with React class components and I just learnt that we need to bind a event handler function in the constructor of the component in order to access this.setState()
inside the event handler. Now from what I understand about JavaScript classes, this
can be accessed by any method inside a class.
To demonstrate what I am saying, here is the code:
class Parent {
setState() {
console.log("Set State is called");
}
}
class Child extends Parent {
eventHandler() {
this.setState();
}
render() {
console.log("Render method called");
console.log("assume an event happened and event handler is called");
this.eventHandler();
}
}
new Child().render()
The output of the above code is:
Render method called
assume an event happened and event handler is called
Set State is called
Contrasting the above code with how react works (i.e. assuming setState
is a method defined in the class React.Component
), why does react throw an error when this.setState()
is called inside an event handler?
The key point I missed out on was that a method that is defined inside a class loses its context when it is reassigned.
So when we do,
<SomeComponent onClick={eventHandler} />
the eventHandler
is reassigned to some other variable and is called internally by react. Because of this reassignment, the eventHandler
will lose its context and when called by react internally, it wont have this
.
To explicitly bind this
to the eventHandler
so that it doesn't lose its context even after reassigning, we do:
this.eventHandler = this.eventHandler.bind(this)
Please refer this article for an in-depth explanation.