Passing Arguments to Event Handlers
Passing Arguments to Event Handlers
1. The Challenge of Custom Arguments
When attaching an event listener in React, passing just the function name works when no extra arguments are needed:
However, in real-world applications, you frequently need to pass custom arguments to your handler—such as an item ID, a user object, or an array index:
Writing deleteItem(course.id) invokes the function during render, triggering premature deletions and potentially infinite re-render loops!
2. Solution 1: Inline Arrow Functions (Standard Modern Pattern)
The most widespread, readable, and idiomatic approach in modern React is wrapping the function call in an inline arrow function:
Accessing Both Custom Arguments and the Event Object (e):
If your handler also needs access to the event object (e.g. to inspect coordinates or prevent default behavior), declare e in the arrow function parameter list:
In the handler definition:
3. Solution 2: Higher-Order Functions (Currying)
In advanced component architectures, you can write a handler that returns another function. This is known as function currying:
4. Performance Considerations with Inline Functions
In older React documentation, developers were warned against creating inline arrow functions (() => doSomething()) due to memory allocation concerns.
In modern JavaScript engines (V8, JavaScriptCore) and modern React:
- Creating small inline functions on render has negligible performance overhead in 99% of applications.
- You should only optimize inline arrow functions (using
useCallback) if passing handlers down to heavily memoized child components (React.memo) that render massive lists. - For standard components, prioritize clarity, readability, and maintainability.
Practice Quiz
<button onClick={handleRemove(item.id)}>Remove</button>?e to a handler?onClick prop acceptable in modern React?Handling Click, Change, and Submit Events
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Handling Synthetic Events in React | Handling Click, Change, and Submit Events |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.