Optional Event Parameters: Making Handlers Reusable
You'll learn how to make event handlers flexible by accepting optional event parameters, allowing the same function to work in multiple contexts.
The Core Idea
Sometimes you want a single handler function that can be called both from an actual DOM event (like a button click) and programmatically from your code without an event object. Making the event parameter optional lets you write one handler instead of two separate functions.
Why This Matters
Imagine a "clear form" handler. You might trigger it when a user clicks a button (passing the event) or when a form successfully submits (no event needed). Without optional parameters, you'd write two nearly-identical functions. With optional parameters, you write one reusable handler.
The Pattern
const handleClear = (event?: React.MouseEvent<HTMLButtonElement>) => {
// Optional chaining in case event is undefined
event?.preventDefault();
// Your actual logic works regardless
resetForm();
clearErrors();
};
// Works with actual click events
<button onClick={handleClear}>Clear</button>
// Works when called programmatically
const onSuccess = () => {
handleClear(); // No event object needed
showSuccessMessage();
};
The ? after event makes it optional. Inside the function, use optional chaining (event?.) to safely access event methods without runtime errors.
Real-World Use Case
This shines when you have shared logic that sometimes originates from user interaction and sometimes from application state changes—like closing a modal via button click or automatically after a timeout.
Key Takeaway: Optional event parameters (event?: React.MouseEvent) let you write handlers that work both as DOM event callbacks and as regular functions, eliminating code duplication when the same logic applies in multiple contexts.