Curried event handlers in React.js
When working with React.js components, you might end up in a situation where you would be using an event handler more than once.
Check the following for example.
import React from 'react';
function MyComponent() {
handleClick(e, count) {
console.log(e, count)
}
render() {
return(
<div>
<a onClick={(e) => handleClick(e, 1)}>Clicked once</a>
<a onClick={(e) => handleClick(e, 2)}>Clicked twice</a>
<a onClick={(e) => handleClick(e, 3)}>Clicked thrice</a>
</div>
);
}
}
As you can tell, we have a functional component called <MyComponent />
and inside this component, there are a few links whose onClick
event is being bound by a handler handleClick
.
Notice, we pass in the event e
and count as the arguments to this handler.
So, if you’re using this at multiple places, this kind of implementation gets quite messy since we are using the arrow function and passing in the event every time we are calling the handler.
There’s a cool little trick that I learned from this video by Fireship.io that can make this a lot concise and cleaner a bit.
The curried handler
The idea here is to use a technique called currying where we can return a function from a function.
Sounds confusing? Let’s rewrite the previous example with the currying technique to give you a better sense of it.
import React from 'react';
function MyComponent() {
handleClick(count) {
return (e) => console.log(e, count);
}
render() {
return(
<div>
<a onClick={handleClick(1)}>Clicked once</a>
<a onClick={handleClick(2)}>Clicked twice</a>
<a onClick={handleClick(3)}>Clicked thrice</a>
</div>
);
}
}
As you can tell, the handleClick
is now a curried function that returns another function. This function handles the event which is passed by default to this inner function. So, we don’t need to explicitly pass in the event when calling the handler.
Also, on top of this, we don’t need to use the arrow function while calling the handler as well. So, this makes things much cleaner as a result!
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.