React-The difference between these two codes syntax: onClick={()=> removeItem(id)}, and onClick={removeItem(id)}
In this post we will look at the difference between these two codes syntax: onClick={()=> removeItem(id)}, and onClick={removeItem(id)}. They both seems to look same, but one will cause the code to fail
The difference between onClick={() => removeItem(id)} and onClick={removeItem(id)} lies in how they handle the function invocation.
onClick={() => removeItem(id)}:
- This approach uses an arrow function within the
onClickhandler. It creates an inline arrow function that, when executed, callsremoveItem(id). - This method is often used to pass arguments to the function. In this case, the arrow function captures the
idand passes it toremoveItemwhen the click event occurs.
<button onClick={() => removeItem(id)}>Click me</button>2. onClick={removeItem(id)}:
- This approach directly invokes the
removeItemfunction during the rendering phase rather than waiting for the click event. It callsremoveItem(id)immediately when the component renders. - This is not the intended behavior for an event handler. In most cases, it will result in an error or unexpected behavior because
removeItem(id)is executed right away, and its result (if any) is assigned toonClick.
<button onClick={removeItem(id)}>Click me</button>In the second case, if removeItem(id) returns a function, that returned function would be assigned to onClick, effectively making it a callback that gets executed during rendering. This is generally not the desired behavior for event handlers, and it's a common mistake to avoid.
Get QA-init’s stories in your inbox
Join Medium for free to get updates from this writer.
The first approach using the arrow function is the more common and appropriate way to handle the onClick event when you need to pass parameters to the function. It ensures that removeItem(id) is only called when the button is clicked, not during the rendering phase.
Additional Example: when there is no parameter passed in the function
- Using Arrow Function (Correct Approach):
<button onClick={() => removeItem()}>Remove Item</button>In this approach, an arrow function is used as the onClick handler. When the button is clicked, the arrow function calls removeItem()
2. With Direct function call(Incorrect Approach):
<button onClick={removeItem()}>Remove Item</button>In this approach, the removeItem() function is directly called when the component renders, not when the button is clicked. This is incorrect for handling click events.
That’s all for today. Please comment and like to stay updated. Happy reading!!!









