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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With