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

2431 views javascript
1

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.

answered question

3 Answers

12

The difference between these two is the first one,

onClick={f()} 

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
5

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
13

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

JD

Please login first before posting an answer.