DEV Community

Discussion on: onClick handlers with Currying (React)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

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.

This is very confused - you are still passing an anonymous function to the onClick event - albeit one created by a higher order function - there are no 'pointers' involved. Also, you haven't curried anything here. Currying is the act of transforming a function that takes multiple arguments into a series of functions that each take 1 argument.

The function you have named myHandler isn't a handler at all - it is a function that creates a handler. It would be better named createHandler.

An example of currying a function:

// 'normal' function style
function add(a, b) {
  return a + b
}
function addCurried(a) {
  return function(b) {
    return a + b
  }
}

// or 'arrow' function style
const add = (a, b) => a + b 
const addCurried = a => b => a + b

// usage
add(1, 2)   // 3
addCurried(1)(2)   // 3
addCurried(7)   // function

const add5 = addCurried(5)
add5(3)   // 8
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jamesthomson profile image
James Thomson

Thank you! I was reading through this and thinking... this isn't currying at all.