DEV Community

Discussion on: What is Currying function? – JavaScript

Collapse
 
unthrottled profile image
Alex Simons

I find currying is handy when I'll eventually need access to a value that isn't quite in scope/not available yet.

My most recent use case was when I needed an on click handler. I needed to be able to reset my form and do other stuff on a button click, but the reset form function wasn't available until the form rendered.

So I just created a function that takes the reset form and returns an on click listener. I found it a nice way to keep things tidy and near the other relevant stuff in scope.

Here is the React snippet:

  const doStuffOnClick =
    (resetForm: (nextState?: any) => void) => () => {
      // do stuff
      // ............
      resetForm({
        values: someValue,
      });
    };

  return (
    <>
      <Formik>
        {({
            resetForm,
          }) => (
          <>
            <Button onClick={doStuffOnClick(resetForm)}>
              Do Stuff
            </Button>
          </>
        )}
      </Formik>
    </>
Enter fullscreen mode Exit fullscreen mode