Avoiding Callback Hell in Event Handlers
You'll learn how scattered logic across multiple event handlers creates unreadable code, and how dispatching named actions can clarify your intent.
The Problem: Callback Hell in Handlers
When your component has complex state that triggers multiple updates, event handlers can become nightmarish chains of setState calls. Imagine a form submission that needs to:
- Validate fields
- Update loading state
- Make an API call
- Handle success or error
- Reset certain fields
- Update submission history
Your handler might look like this:
const handleSubmit = () => {
setIsValidating(true);
setError(null);
setIsSubmitting(true);
setLastAttempt(Date.now());
// ...then more logic with nested callbacks
// ...and more setState calls
// What was I even trying to do?
};
The Clarity Problem
When logic is scattered across multiple useState updates, it becomes hard to understand the intent. What business action is this handler performing? "Submit form" gets lost in a sea of technical state updates.
The Solution: Dispatch Named Actions
Instead of multiple state updates, you dispatch a single action with a meaningful name that describes what you're trying to accomplish:
const handleSubmit = () => {
dispatch({ type: 'SUBMIT_FORM_STARTED' });
// Intent is crystal clear!
};
The reducer handles all the coordinated state changes in one place, making the handler's purpose obvious at a glance.
The Analogy
Think of a restaurant: Instead of the waiter running to the kitchen, adjusting the stove, adding ingredients, and plating the dish (scattered logic), they simply call out "One burger, medium rare!" (dispatch an action). The kitchen (reducer) knows exactly what that means and handles all the steps.
Key Takeaway: When event handlers become cluttered with multiple setState calls, dispatch actions with clear names instead—your handlers become self-documenting, and all related state updates stay together in your reducer.