The onClick={() => func()} Pattern
What you'll learn: When and why to wrap your callback functions in arrow functions when passing them as props.
Why We Need This Pattern
You've learned to pass functions as props, but sometimes you need more control over when and how they execute. The onClick={() => func()} pattern is the solution to two common problems:
- Preventing immediate execution — Writing
onClick={func()}calls the function right away during render, not when clicked - Passing arguments — You can't directly pass arguments in
onClick={func}syntax
The Core Pattern
Think of it like giving someone instructions on a sticky note versus doing the task yourself. When you write:
<button onClick={() => deleteItem(item.id)}>Delete</button>
You're creating a wrapper function that React will call later. The arrow function acts as a middleman: "When clicked, then call deleteItem with this specific ID."
When to Use It
Use the arrow wrapper when:
- You need to pass arguments:
onClick={() => func(arg)} - You want to prevent immediate execution of a function call
Use the direct reference when:
- No arguments needed:
onClick={func} - The function is already set up to receive the event object
Common Scenario
// ❌ Calls immediately on render!
<button onClick={alert('Hello')}>Click Me</button>
// ✅ Calls when clicked
<button onClick={() => alert('Hello')}>Click Me</button>
Key Takeaway: Wrap callbacks in arrow functions () => when you need to pass arguments or prevent immediate execution — you're creating a function that React will call later, not calling it yourself during render.