Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between onClick ={ () => function()} and onClick = {function()}?

What's the difference between this code:

<button onClick={()=>props.submitHandler(searchInputValue)}>Submit</button>

and

<button onClick={props.submitHandler(searchInputValue)}>Submit</button>

The difference is the first one has the parentheses and the second one doesn't. Without the parentheses, my app seems to be re-render indefinitely. Can someone kindly explain it to me?

like image 642
KyoKatarz Avatar asked Aug 26 '26 09:08

KyoKatarz


2 Answers

In first one:

<button onClick={()=>props.submitHandler(searchInputValue)}>Submit</button>

This is arrow function and it will trigger only onClick of the button.

In second one:

<button onClick={props.submitHandler(searchInputValue)}>Submit</button>

This is a normal function call , which calls the method as soon the rendering of the component happens.

like image 81
Harmandeep Singh Kalsi Avatar answered Aug 27 '26 23:08

Harmandeep Singh Kalsi


The first creates a function that calls submitHandler with an argument and assigns that function to onClick.

The second immediately (i.e. during the render step) calls submitHandler with an argument and assigns the return value to onClick.

like image 35
Quentin Avatar answered Aug 27 '26 23:08

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!