Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 7 of 10
Event Handling & Synthetic Events
React wraps native browser events in SyntheticEvent objects - a cross-browser normalized layer. Understanding event delegation, handler patterns, and the synthetic event system prevents subtle bugs and performance issues.
React's Synthetic Event System
// React attaches ONE event listener to the root DOM node (not each element)
// This is EVENT DELEGATION - far more efficient than per-element listeners
// When you click a button:
// 1. Native click event bubbles up to root
// 2. React intercepts it at root
// 3. React wraps it in a SyntheticEvent object
// 4. React dispatches to the correct component handler
function Form() {
// SyntheticEvent is typed - use React's event types in TypeScript
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
console.log(e.target.value); // โ
standard DOM property
console.log(e.target.name); // โ
input name
console.log(e.nativeEvent); // โ
access the raw native event
}
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault(); // prevent default form submission
// process form data...
}
function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === 'Enter') handleSubmit(e as any);
if (e.key === 'Escape') clearInput();
// e.ctrlKey, e.shiftKey, e.altKey also available
}
return (
<form onSubmit={handleSubmit}>
<input
onChange={handleChange}
onKeyDown={handleKeyDown}
name="email"
type="email"
/>
<button type="submit">Submit</button>
</form>
);
}Handler Patterns & Performance
// โ ANTI-PATTERN - inline arrow function creates new function every render
// This is FINE for simple cases, but breaks React.memo on children
{items.map(item => (
<Button key={item.id} onClick={() => handleDelete(item.id)}>Delete</Button>
))}
// โ
BETTER - use data attributes for simple event delegation
function List({ items }: { items: Item[] }) {
function handleDelete(e: React.MouseEvent<HTMLUListElement>) {
const target = e.target as HTMLElement;
const id = target.closest('[data-id]')?.getAttribute('data-id');
if (id) deleteItem(id);
}
return (
<ul onClick={handleDelete}>
{items.map(item => (
<li key={item.id}>
{item.name}
<button data-id={item.id}>Delete</button>
</li>
))}
</ul>
);
}
// Stopping propagation - use sparingly (hides event flow)
function Modal({ onClose }: { onClose: () => void }) {
return (
<div className="overlay" onClick={onClose}>
<div
className="modal"
onClick={(e) => e.stopPropagation()} // โ click inside modal won't close it
>
Modal content
</div>
</div>
);
}
// Capture phase events (fires before bubbling, top-down)
<div onClickCapture={handleCapturePhase}>...</div>Common Mistakes - Event Handling
- Calling handlers instead of passing them: `onClick={handleClick()}` calls the function immediately during render; use `onClick={handleClick}` (pass the reference)
- Accessing synthetic event properties asynchronously - in React 17 and earlier, synthetic events are pooled (properties nulled after handler); if you need async access, call `e.persist()` or store `e.target.value` in a local variable first
- Using `e.stopPropagation()` as a band-aid - it prevents legitimate parent handlers from firing; prefer designing event flow intentionally
- Forgetting `e.preventDefault()` on form submit - without it, the form submits and the page reloads, clearing all React state
- Attaching event listeners with `addEventListener` directly in render - bypasses React's synthetic event system; use `useEffect` with proper cleanup for external event listeners
Tip
Tip
Practice Event Handling Synthetic Events in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Event Handling & Synthetic Events
Practice Task
Note
Practice Task - (1) Write a working example of Event Handling Synthetic Events from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Event Handling Synthetic Events is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Key Takeaways
- React wraps native browser events in SyntheticEvent objects - a cross-browser normalized layer.
- Calling handlers instead of passing them: `onClick={handleClick()}` calls the function immediately during render; use `onClick={handleClick}` (pass the reference)
- Accessing synthetic event properties asynchronously - in React 17 and earlier, synthetic events are pooled (properties nulled after handler); if you need async access, call `e.persist()` or store `e.target.value` in a local variable first
- Using `e.stopPropagation()` as a band-aid - it prevents legitimate parent handlers from firing; prefer designing event flow intentionally
Finished this lesson?