Reputation: 89
I'm having a problem understanding the differences between the function calls below. Specifically in React or any other JavaScript frameworks.
Assuming that func()
is
const func = () => {
console.log("func() called");
return 1;
}
how will these three invocations be different?
<Button onClick={()=>func()} >test</Button>
<Button onClick={func()} >test</Button>
<Button onClick={func} >test</Button>
Thanks!
Upvotes: 0
Views: 60
Reputation: 171
I would like contribute sharing the follow link where you can find extra explanation: https://upmostly.com/tutorials/react-onclick-event-handling-with-examples
Upvotes: -1
Reputation: 26075
There is a huge difference in the way it is evaluated and executed.
<Button onClick={()=>func()} >test</Button>
This will will wrap original function func
in another function and the wrapper function will be bound to the event and will be called.
<Button onClick={func()} >test</Button>
This will invoke function immediately and will bind result of the function call to onClick event.
<Button onClick={func} >test</Button>
This however, will bind func
event to onClick event and will be called when ever even is invoked.
Upvotes: 4
Reputation: 389
Sure!
This creates a new lambda function that calls func during the onClick event:
<Button onClick={()=>func()} >test</Button>
This calls func immediately and assigns the result to onClick. Since func returns a non-function this is an error:
<Button onClick={func()} >test</Button>
Becomes:
<Button onClick={1} >test</Button>
And this assigns func to the onClick handler. It's functionally identical to the first example.
<Button onClick={func} >test</Button>
Upvotes: 2