Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between f() and ()=>f()

I'm confused by this when doing event handling in javascript with ReactJS.

Is there any differences between

<button onClick={f()} />

and

<button onClick={()=>f()} />

what I know is the second one is a wrapping function that return f(), but i don't see what exactly changed there. And I do see both of them in others' code.

like image 360
daryldaryl Avatar asked Nov 08 '18 01:11

daryldaryl


1 Answers

In your example, the first case just calls f at load time, which is probably not what you want unless f returns another function (which would be called when a click event occurs). The second is just an anonymous function wrapping f so that f is not called until the click event happens.

Why is the second notation useful?

If f takes no arguments then using

<button onClick={ f } /> // note: no parentheses

and

<button onClick={ () => f() } />

are pretty much equivalent. There is a slight difference between the two in that the event is passed to f in the first case and is not in the second. Technically <button onClick={ event => f(event) }/> would be equivalent to the first case, but this is somewhat beside the point.

However, if f does take some arguments (other than the event itself), then it's useful to use:

<button onClick={ () => f(someValue) } />

so that someValue can be passed to f when the click event happens.

like image 52
Henry Woody Avatar answered Oct 10 '22 02:10

Henry Woody