Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between the ways of function calls

I have noticed that (at least in React) there are different ways to call a function. I’d say:

onClick={myFunction}
onClick={myFunction()}
onClick={()=>myFunction}
onClick={()=>myFunction()} /*Not sure if I've seen this type*/

Being the case all are correct, what are the difference between them?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

onClick={myFunction}

Assigns myFunction to onClick.


onClick={myFunction()}

Calls myFunction immediately and assigns the return value (which needs to be another function) to onClick.

This is often an error caused by people not understanding how () works and wanting the previous syntax.


onClick={()=>myFunction}

Creates a new function and assigns it to onClick.

The new function mentions myFunction but doesn’t do anything with it. It is a noop.

It is always a mistake.


onClick={()=>myFunction()} 

Creates a new function, which calls myFunction, and assigns it to onClick.

This is usually a waste of resources. It is useful only if myFunction would do something with the event object that onClick passes to the event handler when called and you want to prevent that.

If you were to pass arguments to myFunction (which this example does not) then it would be more generally useful.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading