0

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

DecPK
  • 24,537
  • 6
  • 26
  • 42
villan
  • 11
  • This really depends on how `increase` is defined. If it's a proper react input event handler, the latter will cause an error – Phil Nov 25 '21 at 03:46
  • You can refer this link as well https://stackoverflow.com/questions/49163972/what-is-the-difference-between-passing-a-function-as-a-prop-with-or-without-pare/49164085 – Shubham J. Dec 17 '21 at 08:27

3 Answers3

3

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

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

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.

Dawood Ahmad
  • 476
  • 4
  • 13
0

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.

Refer: Rules of hooks, useCallback

Pranay Binju
  • 591
  • 1
  • 6
  • 14