Reputation: 35
i have a simple question that has border me for a very long time. so can anyone tell me what is the difference between onClick{()=> function()}} and onClick{function()}? what is the difference between having a arrow function and without an arrow function? and are these two function both callback functions?
Upvotes: 1
Views: 44
Reputation: 202667
I believe you meant more what is the difference between onClick={() => callback()}
and onClick={callback}
(notice sans ()
). If you did onClick={callback()}
then the callback would be invoked immediately and not when the click occurs.
onClick={() => callback()}
: An anonymous function is created each time the component is renderedonClick={callback}
: A "reference" to the callback function is passed each render cycle insteadThere isn't much of a difference between the two other than if using the direct reference version it will also be passed the onClick
event, but if the callback doesn't take any arguments anyway this isn't an issue. With the anonymous function there may be higher memory usage (since each component receives a copy of the callback) and some marginal performance hit in constructing the copies.
Using an anonymous callback function allows for other arguments to be passed
onClick={() => callback(customArg)}
Or you can proxy the event object and pass other args
onClick={event => callback(event, customArg)}
You can achieve a similar effect with a direct reference by creating a curried callback function. This allows you to still pass additional arguments and the onClick
event
const callback = customArg => event => {...}
...
onClick={callback(customArg)}
Upvotes: 1