What is the difference between (1) and (2) in React?
onClick={()=>handleDelete(id)} -------(1)
onClick={handleDelete(id)} ----------(2)
why does (2) cause infinite loops whereas (1) works just fine?
I couldn't find any documentation on onClick in react being only able to take in functions. I'm also a bit confused as to how the Html and JS onClick property is different from react So any documentation links will also be highly appreciated.
The code snippet in question:
<button
className="btn btn--danger"
onClick={()=>handleDelete(id)}
>
Delete
</button>
Thanks in advance!
CodePudding user response:
Whatever is in the curly braces is what is returned to the listener. The listener is expecting a function that will be called when the event is fired.
onClick={handleDelete(id)}
This won't work because you're calling handleDelete
immediately and assigning the result of calling that function to the listener. That function may return an explicit value or undefined
(note: that explicit value may be a a new function (closure) which can be assigned to the listener - but in this case I doubt this is happening).
onClick={() => handleDelete(id)}
This will work because you're assigning a function to the listener, and when the event is fired it will call that function which, in turn, will call handleDelete(id)
.
onClick={handleDelete}
This will also work because you're passing a reference to the handleDelete
function to the listener, and that function will get called when the event is fired.
(Note: doing it this way would mean that the component would need to be rewritten to have a data-id
attribute that the function can pick up because you're no longer sending an explicit id
argument to handleDelete
when you call it.)
CodePudding user response:
The second one has mis-matched round braces, could that be why it causes an infinite loop?
CodePudding user response:
before explaining the differences you have a mismatching braces in the second one
The second one is Called invoked function that means when the component mounts the function runs without clicking the button, it will invoke and runs it, and does not wait and will run immediately,and for the other one is callback function it will run when the user click the button