Brief and simple
It is a function which returns another function written in short way.
const handleChange = field => e => {
e.preventDefault()
// Do something here
}
// is equal to
function handleChange(field) {
return function(e) {
e.preventDefault()
// Do something here
}
}
Why people do it ?
Have you faced when you need to write a function which can be customized? Or you have to write a callback function which has fixed parameters (arguments), but you need to pass more variables to the function but avoiding global variables? If your answer "yes" then it is the way how to do it.
For example we have a button
with onClick callback. And we need to pass id
to the function, but onClick
accepts only one parameter event
, we can not pass extra parameters within like this:
const handleClick = (event, id) {
event.preventDefault()
// Dispatch some delete action by passing record id
}
It will not work!
Therefore we make a function which will return other function with its own scope of variables without any global variables, because global variables are evil .
Below the function handleClick(props.id)}
will be called and return a function and it will have id
in its scope! No matter how many times it will be pressed the ids will not effect or change each other, they are totally isolated.
const handleClick = id => event {
event.preventDefault()
// Dispatch some delete action by passing record id
}
const Confirm = props => (
<div>
<h1>Are you sure to delete?</h1>
<button onClick={handleClick(props.id)}>
Delete
</button>
</div
)
Other benefit
A function which returns another function also called "curried functions" and they are used for function compositions.
You can find example here: https://gist.github.com/sultan99/13ef56b4089789a8d115869ee2c5ec47