KyoKatarz
KyoKatarz

Reputation: 111

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?

Upvotes: 6

Views: 11511

Answers (4)

tnvr_98
tnvr_98

Reputation: 121

In first one arrow function returns back a function which is assigned to the onClick

In the second one we call the function when the component renders hence it's not assigned to the onClick handler of the button as function pointer is not returned in the second case.

Upvotes: 0

Bartek
Bartek

Reputation: 21

Remember the fact that a function is assigned to onClick via {} doesn't mean that it will be triggered on html user request. The {} is a compile time action.

Another words: onClick=> {execute what is here at compile time and assign the result into onClick action}

If you have a props.submitHandler() function call inside {} it will be executed and return value assigned to onClick.

If you have a ()=>props.submitHandler it is an arrow function and its execution will be "binded" to onClick user action. Traditional method of doin' it (without using fancy arrow functions) would be

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

Upvotes: 2

Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

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.

Upvotes: 10

Quentin
Quentin

Reputation: 943615

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.

Upvotes: 8

Related Questions