Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to pass function reference instead of method in onClick event of button in ReactJS?

Whenever I pass function parentheses in onClick of button, it automatically calls when page loads even without clicking on button. But when I don't pass function parentheses in onClick of button, it calls only when button is clicked.

With passing parentheses in function call

<button onClick={this.handleButtonClick()}>Increment</button>

Without passing parentheses in function call

<button onClick={this.handleButtonClick}>Increment</button>

Why function called automatically on page load whenever I pass parentheses to function even-though it is written inside onClick of button ?

like image 261
Bhavik Shah Avatar asked Sep 02 '25 15:09

Bhavik Shah


2 Answers

There's a difference between a function call and a function.

When a component renders, all statements are executed and expressions are evaluated. It's plain javascript, that's how javascript works.

this.handleButtonClick() is a function call, and therefore the function will be called once the component renders. I assume that handleButtonClick() returns undefined which will cause the button to render as <Button onClick={undefined} />. Now, if onClick is undefined, nothing will happen when the click actually happens as there is no function to be called.

this.handleButtonClick is just a reference to a function, it doesn't invoke it. You need to pass the function reference to onClick prop so that it can be called later by React, once the click actually happens.

like image 51
Ante Gulin Avatar answered Sep 05 '25 06:09

Ante Gulin


It automatically calls because you are invoking it immediately by:

this.handleButtonClick()

"onClick" does not work like that, if you want to manually invoke the function you can use:

onClick={() => this.handleButtonClick()}

This is done automatically if you use function reference. Hence, you don't need to invoke it or use a callback function. Actually, using function reference is better since that function isn't recreated in every render.

like image 41
devserkan Avatar answered Sep 05 '25 07:09

devserkan