-1
const handleChange = name => event => {
setState({ ...state, [name]: event.target.checked });
};

See the complete code at CodeSandbox.

6899 huge
  • 198
  • 2
  • 12

2 Answers2

3

argumentName => returnValue is shorthand for (argumentName) => {return returnValue;}

So, your code is equivalent to

const handleChange = (name) => {
  return (event) => {
    setState({...state, [name]: event.target.checked});
  }
}

In other words, handleChange is a function which itself returns another function, and that inner function does the setState() call.

If you did this:

const foo = handleChange("Bar");

The value of foo would essentially be this (a function):

foo = (event) => {
  setState({...state, "Bar": event.target.checked});
}

Edit: one thing I'll note is that it could be useful to rename handleChange to something that more accurately describes what it does. For instance:

const createHandleOnChangeFunction = name => event => {
    setState({ ...state, [name]: event.target.checked });
};

Now it's a little more clear what this function does... it creates a function that handles onChange events.

jered
  • 11,220
  • 2
  • 23
  • 34
0

a function that returns a function.

It's like a function factory... where you can build a function where it has ( in this case name ) things preset in the function.

Very common in functional programming.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156