Badal Saibofrontend / ui / ux

Using currying for inline handler functions in React

This is an inline handler function

<div onClick={() => alert('hello')} />

Inline handler functions are the most common way to pass parameters to an exisiting handler function

const handleClick = (param) => {
  alert(param);
};

<div onClick={() => handleClick('guava')} />;

Remember that all a handler function needs is a function.

In JS we can call a function that returns a function. This is known as currying. Wait isn't that HOF too? [1]

const handleClick = (param) => () => {
  alert(param);
};

<div onClick={handleClick('guava')} />;

handleClick('guava') returns a function () => { alert('guava') }. This is a function definition which isn't being executed. This is what onClick is assigned to.

Remember that all a handler function needs is a function.

References

  1. Currying vs HOF