Event Handler Composition
You'll learn how to implement the call-all pattern so both your library's event handler and your user's custom handler execute in sequence without conflicting.
The Problem
When a library component returns props via a prop getter (like getButtonProps()), it often includes its own onClick handler for internal logic. But what if the user also wants to attach their own onClick? Simply passing onClick would overwrite the library's handler, breaking functionality.
The Call-All Pattern
The solution is event handler composition: merge both handlers so they both run. Think of it like a relay race — the library's handler runs first, then passes the baton to the user's handler.
Here's the basic implementation inside your prop getter:
function getButtonProps(userProps = {}) {
return {
onClick: (event) => {
// Library's internal logic runs first
handleToggle();
// Then call user's handler if they provided one
userProps.onClick?.(event);
}
};
}
Why This Matters
This pattern respects separation of concerns: the library controls its internal behavior while giving users full freedom to add their own logic. Both handlers coexist peacefully.
// User can now do this:
<button {...getButtonProps({ onClick: () => console.log('Clicked!') })}>
Toggle
</button>
// Both handleToggle() AND the console.log run
Order Matters
The library typically runs its handler first to ensure correct internal state, then invokes the user's handler. This prevents user code from interfering with critical library operations.
Key Takeaway: Event handler composition via the call-all pattern lets library components execute their required logic while still allowing users to inject custom behavior — the handlers cooperate instead of competing.