Jessie Park
Jessie Park

Reputation: 31

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

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?

Upvotes: 2

Views: 786

Answers (1)

Noah Dennis
Noah Dennis

Reputation: 92

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.

Upvotes: 1

Related Questions