简体   繁体   中英

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

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

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) }} )

One addition to CertainPerformance 's answer - Using onClick={increase} , we can pass a memoized version of the callback by passing the function to useCallback hook.

Like,

const increase = useCallback(()=>{
   //some logic
},[])
...

<Foo onClick={increase} />

This helps in preventing unnecessary rendering of components on re-render of parent and thereby increasing performance.

While in the case of onClick = {()=>{increase()}} , re-rendering of the component will occur every time as new reference to the callback is created on every render of the parent component. Also, we cannot use useCallback here like onClick = {useCallback(()=>{increase()},[])} as useCallback cannot be called inside a callback. We get the error - React Hook "useCallback" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function. React Hook "useCallback" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function.

Refer: Rules of hooks , useCallback

the difference is that:

onClick={increase}

only called the "increase" function, you can not pass an argument 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM