Read with this post
In React, you cannot directly pass a parameter to a handler like because this executes the function immediately during rendering. Instead, you must pass a reference to a function that will execute later.
1. Using Arrow Functions (Recommended)
The most common and readable way to pass parameters is by wrapping the handler call in an anonymous arrow function.
- Standard Argument: .
- With Event Object: If you also need the React event object (e.g., to call ), pass it explicitly through the arrow function:.
2. Using the Method
You can use the JavaScript Function.prototype.bind() method to create a new function with the arguments pre-filled.
- Syntax: .
- Note: In class components, is required as the first argument to maintain context. In functional components, you can pass as the first argument. The React event object is automatically forwarded as the final argument.
3. Using Data Attributes
For performance-critical lists, you can store data in
and retrieve them from the event object.
HTML data-* attributes
and retrieve them from the event object.
- Implementation:
- JSX: .
- Handler: .
- Advantage: Avoids creating a new function instance on every render, which is useful for very large lists.
4. Function Currying
Currying involves creating a function that returns another function. This keeps your JSX cleaner.
- Handler Definition: .
- JSX Usage: .
| Method | Primary Use Case | Performance Impact |
| Arrow Function | Most common, standard applications | Minimal (creates new function on render) |
| .bind() | Class components | Minimal (same as arrow function) |
| Data Attributes | High-performance lists | Best (uses a single function reference) |
| Currying | Clean JSX syntax | Minimal (same as arrow function) |
Caution: Creating functions inside the method (via arrow functions or ) can sometimes cause unnecessary re-renders in child components that use React.memo.
No comments:
Post a Comment