Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
passing event handler as reference

this is an exercise from codecademy. Why does it require to pass the event handler as a reference? why i can't type onClick={goBack()} instead of onClick={goBack}

const goBack = () => {
    setQuestionIndex(prevQuestionIndex => prevQuestionIndex - 1);
  }

....

 <button onClick={goBack}>
          Go Back
 </button>
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

When you are using onClick={goBack()} then you are invoking/calling the function goBack and the result of goBack invocation get passed to onClick

Live Demo

Codesandbox Demo

But If you are using as onClick={goBack}, then In this case you are passing a reference to the onClick which means when user click on the button then It will automatically invoke the function. You don't have to invoke the function yourself.


1) Let say consider function with value

<button onClick={fun()}> button with function reference</button>

If you are passing value to a function then first of all it will produces a warning in the console as:

Warning:
Expected `onClick` listener to be a function, instead got a value of `string` type.

and when you invoke it then it will throw error as

Error
Expected `onClick` listener to be a function, instead got a value of `string` type.

2) If you are using as

<button onClick={fun}> button with function reference</button>

then function fun will be passed as a prop and when use click on the function then this function fun will get invoked automatically

about 4 years ago · Juan Pablo Isaza Report

0

goBack is a reference to a function, goBack() calls that function and returns the result.

In the case of the click handler for a button, of course, you want the function to run when the button is clicked, not when the button is rendered. That's why you need to pass the function, rather than calling it (on render) and passing its result.

about 4 years ago · Juan Pablo Isaza Report

0

If you pass in the function call instead of the reference, it will call the function as soon as your component renders, the reference is bound to the click handler, hence when the specific event triggers, it will callout to the reference.

Here is a snippet to see this, Sandbox

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!