Home > Net >  Difference between onClick={function()} and onClick={()=>function()} in React
Difference between onClick={function()} and onClick={()=>function()} in React

Time:01-16

when trying to call this function onClick,

function changeProfile(e){setProfilePic(e)}

when I use onClick={changeProfile(props)}, it calls the function whenever the page is loaded, and doesn't work properly as it calls all the props at once even the ones that are not called. onClick={()=>{changeProfile(props) this works exactly how I imagined, calling only the component that is clicked. What is the difference between the two and when do I use the specific method of {()=>function}??

I know that it works now, but what is the exact difference between the two?

CodePudding user response:

onClick={()=>{changeProfile(props) will register an event handler to the click event.

onClick={changeProfile(props)} will run when it is encountered in the code. This is why it occurs on the page load.

CodePudding user response:

It has nothing to do with React or JSX really. It is what is inside {} is just a regular JS expression.

<button onClick={()=>{changeProfile(props) />

Here it is only pointing to the function. This will not execute it here. It will only execute when user clicks on that button

<button onClick={changeProfile(props)} /> 

This will execute the function when it is encountered in the code. This is why it occurs when component renders for the first time and we did not even click on that button.

  • Related