Encapsulating Validation and Constraints
What you'll learn: How reducers can enforce validation rules and constraints that prevent invalid state, which useState allows to slip through.
The Problem with useState
When you manage state with multiple useState calls, each setter function works independently. There's nothing stopping you from setting a counter to -5 when it should never go below zero, or setting a percentage to 150 when the valid range is 0-100. You have to remember to add validation in every event handler that updates state — and it's easy to forget one spot.
// With useState: validation is scattered and optional
function Counter() {
const [count, setCount] = useState(0);
const decrement = () => {
setCount(count - 1); // Oops! Can go negative
};
const increment = () => {
setCount(count + 1); // Could exceed max
};
}
How Reducers Enforce Constraints
A reducer acts as a gatekeeper for all state changes. Every update must go through it, making it the perfect place to centralize validation logic. The reducer can reject invalid transitions, clamp values to valid ranges, or transform inputs to meet constraints — before the state ever updates.
function counterReducer(state, action) {
switch (action.type) {
case 'increment':
// Enforce maximum constraint
return { count: Math.min(state.count + 1, 100) };
case 'decrement':
// Enforce minimum constraint
return { count: Math.max(state.count - 1, 0) };
default:
return state;
}
}
Now it's impossible for the count to go below 0 or above 100. The validation lives in one place, gets tested once, and applies to every state update automatically.
Key Takeaway: Reducers centralize validation and constraints, making impossible states truly impossible rather than merely discouraged.