water
water

Reputation: 35

simple questions of callbacks with and without an array function

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

Answers (1)

Drew Reese
Drew Reese

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 rendered
  • onClick={callback}: A "reference" to the callback function is passed each render cycle instead

There 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

Related Questions