0

I've noticed that sometimes a function callback is passed to a component it takes two forms:

<Component onPress={() => handleSomething} />
<AnotherComponent onPress={(val) => handleValue(val)} />

and sometimes:

<Component onPress={handleSomething} />
<AnotherComponent onPress={handleValue(val)} />

Within functional components, is the arrow function version the same as directly calling the function? If not, what are the differences or when one would use them?

Thanks

Wasteland
  • 4,889
  • 14
  • 45
  • 91
  • 1
    First version is buggy -- you'll need to call `handleSomething()` with parentheses, but I think I follow your point anyway. Top versions are slower and probably no more readable. They allocate an extra object on every render which can be expensive. [Dupe suggestion](https://stackoverflow.com/questions/50375440/binding-vs-arrow-function-for-react-onclick-event) is not great because you're likely dealing with a functional component but the same idea applies. See also [Correct use of arrow functions in React](https://stackoverflow.com/questions/48699573/correct-use-of-arrow-functions-in-react) – ggorlen May 28 '21 at 18:02
  • 1
    Does this answer your question? [Binding vs arrow-function (for react onClick event)](https://stackoverflow.com/questions/50375440/binding-vs-arrow-function-for-react-onclick-event) – ggorlen May 28 '21 at 18:02
  • 1
    I guess from what you posted and the links it looks like within the context of functional components the only difference is the fact that the arrow form creates the object on each render. It makes a bigger difference (ie. binding) when it comes to class components, which I'm not really interested in. Thanks – Wasteland May 28 '21 at 21:35

0 Answers0