onClick handlers with Currying (React)
Nitsan Cohen
Posted on January 20, 2022
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) } />
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}`)
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.
Posted on January 20, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.