3 ms·
Here's the simplest example I can come up with, and it's something I do all the time. I have an array of objects in my state. For this example we'll say they a
by coltonv 9y ago
Here's the simplest example I can come up with, and it's something I do all the time.
I have an array of objects in my state. For this example we'll say they are Todos, and each one has three properties, id, name, and checked. I have a function `checkTodo` with the signature `checkTodo(id: string, event: InputEvent)` that I want to call if one of those Todos is checked.
So say I'm using React. I can use arrow functions like this:
todos.map((todo) =>
<input type="checkbox" onChange={ (event) => checkTodo(todo.id, event) } checked={ todo.checked } />
<label>{ todo.name }
)
That's okay, but having arrow functions like that in JSX (which you'll have several of in a complex application) can get a bit unwieldy. Currying gives us another option that can be cleaner and avoids having to declare functions inside our render. If we change our method signature to this: `checkTodo = (id: string) => (event: InputEvent)` then we can write our JSX like this:
todos.map((todo) =>
<input type="checkbox" onChange={ checkTodo(todo.id) } checked={ todo.checked } /><label>{ todo.name }
)
It's a bit cleaner, and can make certain patterns a lot easier in the long run. For example, say we make a shared <Todo /> component like the one above which can be rendered both in a list, as above, or on it's own. In that case, it would be bad for the method signature that the Todo component expects to be the id and event, as the id wouldn't be necessary when we're not working with an array.
Instead, currying means our Todo component can simply expect a function that takes in an InputEvent, and currying can move the other logic where it's needed.
Does that make sense? If you don't know React I could rewrite this using native DOM calls.