Co-locating Related Updates
What you'll learn: How useReducer prevents bugs by grouping state changes that must happen together.
The Problem with Scattered Updates
When changing one piece of state requires changing another, useState forces you to remember both updates in every place they're needed. Forget one update, and your UI state becomes inconsistent.
Imagine a form where selecting "Other" for country should clear the selected city (cities don't apply to "Other"). With multiple useState calls, you must remember:
const [country, setCountry] = useState('USA');
const [city, setCity] = useState('');
function handleCountryChange(newCountry) {
setCountry(newCountry);
// Easy to forget this required update!
if (newCountry === 'Other') {
setCity('');
}
}
Miss that second line anywhere in your code, and city remains set when it shouldn't be.
How useReducer Enforces Relationships
A reducer centralizes these coupled updates in one place. The relationship between country and city lives in the reducer logic, not scattered across handlers:
function reducer(state, action) {
switch (action.type) {
case 'country_changed':
return {
...state,
country: action.country,
// Automatically enforce the rule
city: action.country === 'Other' ? '' : state.city
};
}
}
Now every country change automatically applies the city-clearing rule. You can't forget it because the logic exists in exactly one location.
The Analogy
Think of useState as sticky notes on different desks—you must visit each desk to update related information. useReducer is like a single processing center where all related paperwork gets handled together according to documented procedures.
Key Takeaway: When field A's changes require updating field B, useReducer co-locates that relationship in one place, preventing the "forgot to update the other field" bug that plagues scattered useState calls.