Why do we bind event handlers in React???

azazeloss

Asad Mahmood

Posted on February 19, 2022

Why do we bind event handlers in React???

What is "bind" in Javascript?

Bind is a method inside Function.Prototype which returns a new function whose this keyword's value is set to the value which was passed to the bind method via the parameters.
Example:

Example code for bind method

In this example, the this keyword of the handleEvent function was changed to the this keyword value of the current context.

But why do we need it in react?

In Class Components in React, we usually pass the event handlers as the callbacks which in turn perform certain actions after the event has taken place. But as we all know, callbacks tend to lose the context which called them(also known as implicitly bound context). To preserve the context we bind the context and then are able to use it inside the event handler.


We don't need to worry about the context when we are using arrow functions (after they were introduced in ES6), because they automatically bind to the scope which called them and hence we don't need to explicitly bind them with the current scope.


💖 💪 🙅 🚩
azazeloss
Asad Mahmood

Posted on February 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related