Home > OS >  What is the difference between onClick={increase} and onClick={()=>{increase()}} in React JSX?
What is the difference between onClick={increase} and onClick={()=>{increase()}} in React JSX?

Time:11-25

I did a search and didn't find any results, so I'm asking here.

CodePudding user response:

If the increase function takes no arguments, there is no difference.

The only way there would be a difference would be if the component in which this prop is defined used the value returned from inside the onClick function. For example, for the general case:

<Foo fn={fn} />
<Foo fn={() => { fn() }} />

Those two are not equivalent, because the first will return the return value of fn to Foo, and the second will return undefined to Foo. If Foo uses the return value of its fn prop, you'll see a difference.

But for the onClick prop in React, the return value doesn't matter, and is ignored - so you may as well use onClick={increase} to save on a few characters.

If the increase function does take arguments, then doing

onClick={increase}

will pass along the click event to the function, but

onClick={() => { increase() }}

will not pass anything to the function.

(to pass the event to the function with the anonymous inline form, you'd need onClick={(e) => { increase(e) }})

CodePudding user response:

the difference is that:

onClick={increase}

only called the "increase" function, you can not pass an argument except "Event" to "increase" function by this method, and also you can call only this one function, but when you use:

onClick={()=> {
increase(argument1, argument2,...);
secondFunction();
thirdFunction();
//and so many other functions
}
}

you can pass arguments to your functions, and also you can call other functions as well.

  • Related