Search code examples
javascriptreactjsreact-nativefrontendweb-frontend

React - What's the difference between {doThisFunc} , {doThisFunc()} and {()=>doThisFunc()} as onClick parameter?


I'm completely new to react and kind of mediocre in JS. Just want to know what's the difference between giving a button these parameters for its onClick event :

  • onClick={doThisFunc}
  • onClick={doThisFunc()}
  • onClick={() => doThisFunc()}

Recently I just got a bug where I call a function with parameter like onClick={doThisFunc(a)} and the application went "Too many re-renders. React limits the number of renders to prevent an infinite loop". But then I changed it to onClick={() => doThisFunc(a)} and It works perfectly.

Sorry for such beginner question and many Thanks for your feedback!


Solution

  • onClick={doThisFunc}

    This means "pass the function into the onclick prop". Later, when the click happens, react will call doThisFunc, passing in the click event. This is usually the right thing to do, assuming you want the function to receive the click event.

    onClick={doThisFunc()}

    This means "call the function immediately, and pass its return value into the onclick prop". This is usually a mistake. You would only do this if doThisFunc was a factory that creates click-handler functions, which is rare.

    onClick={() => doThisFunc()}

    This means "create a new function with the text () => doThisFunc(), and pass it into onClick". Later, when the click happens, react will call your new function, which will in turn call doThisFunc.

    This approach is sometimes just a more verbose way of getting the same end result as option 1. But it does have the benefit that you can pass whatever values you want into doThisFunc, so if you want something other than the event to be passed in, you would use this.