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

2431 views javascript

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

Is there any differences between

<button onClick={f()} />


<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.

answered question

3 Answers


The difference between these two is the first one,


means that the return value of the f function will be executed on the onClick event.

Whereas the second example,

onClick={() => f()}

will execute the function f itself on the onClick event.

posted this

First example is a singular method call

<button onClick={f()} />

Second example is a singular method call where wrapper method can call multiple methods and store variables within this scope.

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

posted this

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


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

are equivalent.

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.

posted this

Have an answer?


Please login first before posting an answer.