Passing Dispatch Instead of Multiple Setters
What you'll learn: How one dispatch function simplifies component APIs compared to passing multiple setState functions as props.
The Problem with Multiple Setters
Imagine you have a form component with five pieces of state: name, email, age, country, and isSubscribed. Using useState for each, you'd need to pass five different setter functions down to child components:
function ParentForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [age, setAge] = useState(0);
const [country, setCountry] = useState('');
const [isSubscribed, setIsSubscribed] = useState(false);
return (
<FormFields
setName={setName}
setEmail={setEmail}
setAge={setAge}
setCountry={setCountry}
setIsSubscribed={setIsSubscribed}
/>
);
}
That's five props just for updating state! The component's API becomes cluttered and harder to maintain.
The Cleaner Solution: One Dispatch
With useReducer, you get a single dispatch function that handles all state updates:
function ParentForm() {
const [state, dispatch] = useReducer(formReducer, initialState);
return <FormFields dispatch={dispatch} />;
}
Now you're passing one prop instead of five. Child components call dispatch with action objects describing what should change:
dispatch({ type: 'SET_NAME', payload: 'Alice' });
dispatch({ type: 'SET_EMAIL', payload: 'alice@example.com' });
The Mental Model
Think of dispatch as a universal remote control. Instead of having five separate remotes (setters) for five devices (state pieces), you have one remote that can control everything by sending different commands (actions).
Key Takeaway: Using useReducer's single dispatch function creates cleaner component interfaces than passing multiple setState functions, especially when managing several related pieces of state.