onClick handler calls

Greetings! I’ve been following some React tutorials while working on the projects for the Front End Development course, and on one of them I notice 2 different ways to call functions in onClick. They follow as so:

onClick={() => handleQuit()}

onClick={handleNext}

onClick={handleSubmit()}
(EDIT: Above one striken through due it not being correct)

(each are in separate button’s)
When I was following along, I accidentally called the handleQuit and HandleNext as:

onClick={handleQuit()}

onClick={handleNext()}

which caused me to get the error:

Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

yet when I changed them to the first way I showed, that error went away.

How exactly do these 2 ways of calling method differ from each other? and Why did it cause issues when I did it the “wrong” way?

The last one is just wrong.

Using parentheses will invoke (run) the function. The only time you use that syntax is with inline handlers in plain JS because they just take a string of code to be run when the event triggers.

<button onclick="someFunction()"></button>

For pretty much all other cases you pass the definition (the name) of the handler/callback function and it gets invoked by the event triggering. Just like you do with other callbacks, like with array methods, etc.

Looking back on the code I did indeed read it incorrectly, it was in fact just

onClick={handleSubmit}

I’ll edit the wrong one out

Just an FYI, if you edit the post the thread loses its context. But as there is still an example of the code in your question, I guess it’s fine.


If you are now asking what the difference is between the first two handlers.

Then the first is wrapping the call to the function inside an arrow function definition. So what is passed as the handler is still just a function definition. When that function is called it, in turn, calls the function inside it.

Usually, you use that syntax when you have to pass arguments to the function.

<Button onClick={() => handlerFn(someArgument)}>Click</Button>

The other one is just how you normally pass handlers.

Good to know! I edited it again to re include the last one just stricken through

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.