Proper event handling in React is crucial for interactive applications. Here's how to do it right.
Basic Event Handling#
Passing Arguments#
Event Pooling (Legacy)#
Preventing Default#
Stop Propagation#
Keyboard Events#
Focus and Blur#
Touch Events#
TypeScript Event Types#
Debounced Events#
Event Delegation#
Custom Event Hooks#
Best Practices#
Handlers:
✓ Use named functions for readability
✓ Extract complex logic to functions
✓ Keep handlers close to usage
✓ Use useCallback when passing down
Performance:
✓ Avoid inline arrow functions in lists
✓ Use event delegation for many items
✓ Debounce frequent events
✓ Memoize callbacks appropriately
TypeScript:
✓ Use proper event types
✓ Type event.target correctly
✓ Use generic handlers when needed
✓ Prefer React event types
Avoid:
✗ Inline handlers for complex logic
✗ Missing preventDefault when needed
✗ Ignoring cleanup in useEffect
✗ Unnecessary event.stopPropagation
Conclusion#
React event handling is straightforward but has nuances. Use named handlers for clarity, proper TypeScript types for safety, and patterns like debouncing for performance. Understand event bubbling and when to use preventDefault and stopPropagation. For complex scenarios, create custom hooks that encapsulate event logic and cleanup.