DEV Community

Cover image for Main differences between the two common ways of passing in a functional based prop-value in React with respect to buttons.
Emmanuel Chikwendu Onah
Emmanuel Chikwendu Onah

Posted on • Updated on

Main differences between the two common ways of passing in a functional based prop-value in React with respect to buttons.

Note: for this article, we will be using the button and its onClick property aka attribute or prop.

The main difference between passing in a function to be executed on an operation based(e.g: on button click) and invoking it to executed at render time in React is that "one waits for an action to execute it" and "one executes itself at render time" e.g:

   <button onClick ​={func()}>Button</button> : this will execute at render time then the essence of click event will be abused which is not what you want. 

   <button onClick ​={func}>Button</button> : this will be executed when a button click is triggered.
Enter fullscreen mode Exit fullscreen mode

Note: this is a pure JavaScript thingy and has nothing to do with react.

This is a similar behavior below:
Alt Text

To rewrite this <button onClick ​={func()}>Button</button> in the case of  legacy code:

<button onClick ​={()=>func()}>Button</button> /***what is actually happening here is pure javascript logic which means:

1. A function can only run when its invoked and the anonymous  function of the button which is “()=>” will only run when the invoker(the click event is the invoker) invokes it.
2. It's only when a function is invoked that the internal operation will be executed, meaning it's only when the anonymous function runs that it will execute the "func()".**/


So thank you for stopping to read this ☕️ 👨🏿‍💻🙂
Enter fullscreen mode Exit fullscreen mode

Meanwhile let me give you a little clue as my appreciated follower: So i haven't been releasing articles for a while now because i started contributing to an open-source javascript/react library during my freetimes/weekends after work. So the clue is that,you should get ready to use alot of wonderful and mighty open-sourced projects which will be coming your way soon from "elegant-ui library" a library with contributors from Sony-ericsson, check24,Twilio,myself and....🍾 🍻

Top comments (0)