onClick handlers with Currying (React)

nitsancohen770

Nitsan Cohen

Posted on January 20, 2022

onClick handlers with Currying (React)

How do you pass a function with an argument to an onClick event in React?

You are probably all familiar with the fact that when passing a function that takes an argument to an onClick event (or any other event), you have to wrap it with an anonymous callback function.

For instance:

<button onClick = { () => myFunction(argument) } />
Enter fullscreen mode Exit fullscreen mode

We do it because we want to have a pointer to a function triggered upon a click. If we pass the function without a callback, it will get fired right when the DOM is mounted.

But there is another option. We can pass an anonymous callback to our handler. This way, our handler itself will serve as a pointer, and we will not have to give an anonymous function to our onClick event. The name of this design pattern is called currying.

const myHandler = (text:string) => () => alert(`${text}`)
Enter fullscreen mode Exit fullscreen mode

When is this useful?

It could be helpful when we intend to use our handler in many events (for example, mapping an array). Instead of creating useless callback functions for each event, we create them only once in the handler.

currying react example

💖 💪 🙅 🚩
nitsancohen770
Nitsan Cohen

Posted on January 20, 2022

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

Sign up to receive the latest update from our blog.

Related