Common Use Cases: Preventing Transitions
What you'll learn: How to use the state reducer pattern to block specific state changes, like preventing a modal from closing when clicking outside in certain scenarios.
The Problem
Sometimes your component's default behavior isn't appropriate in all contexts. Imagine a modal that normally closes when you click outside—but when there's unsaved form data, you want to block that close action and show a confirmation dialog instead. The state reducer pattern gives consumers this veto power.
How It Works
With a state reducer, the consumer can intercept any state change before it happens. They can:
- Prevent it entirely by returning the current state unchanged
- Modify it by returning different state
- Allow it by returning the proposed changes
function useDialog(reducer?: (state, changes, action) => State) {
// Inside your component, before applying state:
const newState = reducer
? reducer(state, proposedChanges, action)
: proposedChanges;
}
// Consumer blocks outside clicks when form is dirty:
function App() {
const [isDirty, setIsDirty] = useState(false);
const dialogReducer = (state, changes, action) => {
if (action.type === 'CLOSE_ON_OUTSIDE_CLICK' && isDirty) {
// Block the transition
return state; // unchanged
}
return changes; // allow everything else
};
const dialog = useDialog(dialogReducer);
}
Real-World Scenarios
- Prevent close on outside click when forms are dirty
- Block specific tab switches when validation fails
- Disable certain toggle states based on business rules
- Control maximum values in counters or sliders
The consumer gets surgical control without the library anticipating every edge case with props like preventCloseWhen, blockTransitionsIf, etc.
Key Takeaway: The state reducer pattern lets consumers act as gatekeepers, blocking or modifying state transitions based on their own application logic without cluttering the component's API with endless boolean flags.