Event handlers like onChange
and onClick
pass the "onX" event to the attached handlers. Such is the case with onChange={handleChange}
where handleChange
clearly accepts the event and destructures target
value.
const handleChange = ({target}) => {
console.log(target.value);
}
Same as
const handleChange = (event) => {
const { target } = event;
console.log(target.value);
}
In other cases where the attached callback may not care to receive the event object, or the callback accepts a different argument then you'll see an anonymous function used, as is the case with the first snippet.
onClick={() => setColor('green')}
Here setColor
is a state update function and we want to explicitly pass the value "green" to it. If you were to do onClick={setColor}
then the click event object would be passed to the state updater and saved in state, which isn't the desired behavior.
You will also come across some code examples or code where some dev does:
onClick={(e) => myCallback(e)}
But as shown above, this can quite simply be expressed more directly as
onClick={myCallback}
The point I want to show here is that when the function signature of the callback matches the function signature of the handler that an anonymous function isn't necessary for the code to function properly. It is rather when there is a "mismatch" between them that a "proxy" function is necessary to mate the callback to the handler.