Behavioral Design Patterns in TypeScript: Observer, Strategy, Command, State
Observer, Strategy, Command, State, and Mediator in TypeScript: which ones the language already covers, and when RxJS, Redux, or XState earn their place.
Behavioral patterns define how objects communicate and distribute responsibilities. The Gang of Four documented Observer, Strategy, Command, State, and Mediator for C++ and Smalltalk, languages where each one cost a page of boilerplate before it did anything useful. TypeScript changed that arithmetic. First-class functions, closures, and discriminated unions cover several of these patterns outright, and RxJS, Redux, and XState absorbed most of the rest into framework conventions.
The default that falls out is simple: implement the pattern with a language feature first, and escalate to a library only when a named capability forces it. A function is enough for Strategy, a discriminated union for State, a subscribe list for Observer. Each escalation has its own trigger: operator composition, cancellation, and backpressure justify RxJS; serializable, replayable action history justifies Redux; guarded transitions that reviewers need to read as a chart justify XState, and absent those triggers, the library only adds overhead for something the language already gives you.
Observer Pattern: From Callbacks to Reactive Streams#
The Observer pattern enables one-to-many dependency relationships where changes in one object trigger updates in dependent objects. It is probably the most influential pattern in modern web development, even though it rarely appears under that name.
Subject-Observer Boilerplate#
Observer’s original form requires explicit subject-observer relationships:
interface Observer {
update(data: any): void;
}
class Subject {
private observers: Observer[] = [];
subscribe(observer: Observer): void {
this.observers.push(observer);
}
unsubscribe(observer: Observer): void {
const index = this.observers.indexOf(observer);
if (index !== -1) {
this.observers.splice(index, 1);
}
}
notify(data: any): void {
this.observers.forEach(o => o.update(data));
}
}
// Usage
class ConcreteObserver implements Observer {
update(data: any): void {
console.log('Received update:', data);
}
}
const subject = new Subject();
const observer = new ConcreteObserver();
subject.subscribe(observer);
subject.notify({ value: 42 });
The subject-observer pair covers the basic case, but backpressure handling, error propagation, completion signals, and operator composition are missing entirely.
Node.js EventEmitter Evolution#
Node.js introduced EventEmitter, a more flexible observer implementation:
import { EventEmitter } from 'events';
class DataStream extends EventEmitter {
start(): void {
setInterval(() => {
this.emit('data', { timestamp: Date.now() });
}, 1000);
}
}
const stream = new DataStream();
stream.on('data', (data) => {
console.log('Received:', data);
});
stream.on('error', (error) => {
console.error('Error:', error);
});
stream.start();
EventEmitter improved on classic Observer with:
- Named events instead of single notification method
- Multiple listeners per event
- Error event support
- Familiar
.on()and.emit()API
Node.js also covers cancellation and cleanup. events.on() turns an event into an async iterator that stops when an AbortSignal fires, and it removes all its listeners when the loop exits:
import { on } from 'node:events';
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
try {
for await (const [data] of on(stream, 'data', { signal: controller.signal })) {
console.log('Received:', data);
}
} catch (error) {
// Aborting the signal ends the loop with an AbortError
if (error instanceof Error && error.name === 'AbortError') {
console.log('Stopped listening');
} else {
throw error;
}
}
events.once() takes the same signal option for a single event. What EventEmitter still lacks is an operator vocabulary: it has no built-in debounce or map, and no operator that merges two event sources into one.
RxJS Takes Observer Further#
RxJS (Reactive Extensions for JavaScript) represents the full evolution of Observer pattern into reactive programming:
import { Observable, Subject, of } from 'rxjs';
import {
debounceTime,
distinctUntilChanged,
map,
filter,
catchError
} from 'rxjs';
// Search input with reactive operators
const searchInput$ = new Subject<string>();
searchInput$.pipe(
debounceTime(300), // Wait 300ms after typing stops
distinctUntilChanged(), // Only if value changed
map(term => term.toLowerCase()),
filter(term => term.length >= 3), // Min 3 characters
catchError(error => {
console.error('Search error:', error);
return of([]); // Must return Observable
})
).subscribe(term => {
console.log('Searching for:', term);
// Fetch search results
});
// Emit values
searchInput$.next('rea');
searchInput$.next('react');
searchInput$.next('reactive');
Node’s async helpers give EventEmitter cancellation, but RxJS puts all of these behind one subscribe contract:
- Composable operators: Chain transformations declaratively
- Error handling: Errors propagate through the stream
- Completion signals: Know when stream finishes
- Backpressure: Handle fast producers with operators like
throttle - Cancellation: Unsubscribe stops execution and runs teardown logic
- Hot vs Cold: Control when execution starts
Streaming Prices Over a WebSocket#
A live stock price feed puts those operators to work at once:
import { Observable, Subject } from 'rxjs';
import {
filter,
groupBy,
map,
mergeMap,
pairwise,
repeat,
retry,
scan,
share,
takeUntil
} from 'rxjs';
interface StockPrice {
symbol: string;
value: number;
timestamp: number;
}
// WebSocket as Observable
function createStockStream(url: string): Observable<StockPrice> {
return new Observable<StockPrice>(subscriber => {
const ws = new WebSocket(url);
ws.onmessage = (event) => {
try {
subscriber.next(JSON.parse(event.data) as StockPrice);
} catch (error) {
subscriber.error(error);
}
};
ws.onerror = (error) => {
subscriber.error(error);
};
// A normal server-side close completes the stream
ws.onclose = () => {
subscriber.complete();
};
// Teardown runs when the last subscriber leaves
return () => {
console.log('Closing WebSocket connection');
ws.close();
};
});
}
const stockPrices$ = createStockStream('wss://stocks.example.com').pipe(
// Errors: reconnect up to 3 times, 1s apart; a healthy message resets the count
retry({ count: 3, delay: 1000, resetOnSuccess: true }),
// Normal close: open a new connection after 1s
repeat({ delay: 1000 }),
// One connection for every observer below
share()
);
// Emits once when the component unmounts
const destroy$ = new Subject<void>();
// Observer 1: Update AAPL chart
stockPrices$.pipe(
filter(price => price.symbol === 'AAPL'),
map(price => price.value),
takeUntil(destroy$)
).subscribe(value => {
updateChart('AAPL', value);
});
// Observer 2: Calculate portfolio total
stockPrices$.pipe(
scan(
(acc, price) => ({ ...acc, [price.symbol]: price.value }),
{} as Record<string, number>
),
map(prices => calculatePortfolioValue(prices)),
takeUntil(destroy$)
).subscribe(total => {
updatePortfolioDisplay(total);
});
// Observer 3: Alert on significant changes, compared per symbol
stockPrices$.pipe(
groupBy(price => price.symbol),
mergeMap(symbolPrices$ => symbolPrices$.pipe(pairwise())),
map(([previous, current]) => ({
symbol: current.symbol,
change: current.value - previous.value
})),
filter(({ change }) => Math.abs(change) > 10),
takeUntil(destroy$)
).subscribe(alert => {
showNotification(`${alert.symbol} moved ${alert.change}`);
});
// On unmount: every chain above completes, share() drops to zero
// subscribers, unsubscribes from the source, and the socket closes
function cleanup() {
destroy$.next();
destroy$.complete();
}
Every chain ends with takeUntil(destroy$), so cleanup() completes all three observers at once. share() counts subscribers, and when that count drops to zero it unsubscribes from the source, which runs the teardown and closes the socket. A chain without takeUntil would keep the count above zero and the socket open after unmount. The two reconnect operators cover different exits: retry resubscribes only when the source errors, while a server that closes the socket normally triggers complete(), which only repeat handles. The alert observer uses groupBy and pairwise so it compares each price with the previous price of the same symbol, without a lookup table kept outside the stream.
Redux and Zustand as State Observers#
Redux implements Observer pattern for application state management:
import { configureStore, createSlice, PayloadAction } from '@reduxjs/toolkit';
interface User {
id: string;
name: string;
}
interface AppState {
count: number;
user: User | null;
}
// Modern Redux Toolkit approach (createStore is deprecated)
const appSlice = createSlice({
name: 'app',
initialState: { count: 0, user: null } as AppState,
reducers: {
increment: (state) => {
state.count += 1;
},
decrement: (state) => {
state.count -= 1;
},
setUser: (state, action: PayloadAction<User>) => {
state.user = action.payload;
}
}
});
const { increment, decrement, setUser } = appSlice.actions;
const store = configureStore({
reducer: appSlice.reducer
});
// Subscribe (observe) state changes
const unsubscribe = store.subscribe(() => {
const state = store.getState();
console.log('State changed:', state);
// Update UI based on new state
});
// Dispatch actions
store.dispatch(increment());
store.dispatch(setUser({ id: '1', name: 'John' }));
// Later: cleanup
unsubscribe();
React-Redux turns components into observers through hooks, the API its docs recommend as the default. useSelector subscribes to the store, runs the selector after every dispatched action, and re-renders the component only when the selected value changes by === comparison:
import { useDispatch, useSelector } from 'react-redux';
function Counter() {
// Re-renders only when state.count changes
const count = useSelector((state: AppState) => state.count);
const dispatch = useDispatch();
return (
<div>
<button onClick={() => dispatch(decrement())}>-</button>
<span>{count}</span>
<button onClick={() => dispatch(increment())}>+</button>
</div>
);
}
Zustand keeps the same subscribe-and-notify idea with hooks and far less boilerplate:
import { create } from 'zustand';
interface StoreState {
count: number;
user: User | null;
increment: () => void;
decrement: () => void;
setUser: (user: User) => void;
}
// Create store (subject)
const useStore = create<StoreState>((set) => ({
count: 0,
user: null,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
setUser: (user) => set({ user })
}));
// Component automatically observes relevant state
function Counter() {
// Only re-renders when count changes
const count = useStore(state => state.count);
const increment = useStore(state => state.increment);
const decrement = useStore(state => state.decrement);
return (
<div>
<button onClick={decrement}>-</button>
<span>{count}</span>
<button onClick={increment}>+</button>
</div>
);
}
The store above gives the same selective re-rendering with less code around it. Components subscribe through the store hook and re-render only when the state they select changes. There are no action creators, no reducers, and no Provider, while type inference still works end to end and the middleware layer covers DevTools, persist, and immer.
Choosing an Observer Variant#
| Tool | Reach for it when |
|---|---|
| RxJS | Complex async coordination across multiple streams, advanced operators (debounce, throttle, retry), WebSocket or SSE connections, event stream processing, or backpressure handling is critical |
| Redux | Large application with complex state, time-travel debugging, many components accessing the same state, or the middleware ecosystem (sagas, thunks) matters and the team knows Redux patterns |
| Zustand | Medium-sized application that wants simplicity over features, minimal boilerplate preferred, TypeScript support a priority |
| Plain EventEmitter | Node.js backend services, simple pub/sub within a module, no need for operators or backpressure, minimal dependencies preferred |
Strategy Without the Class Hierarchy#
Strategy pattern picks an algorithm at runtime. TypeScript’s first-class functions mean it rarely needs a class hierarchy to do that: a plain function usually works better.
Interface-Based Payment Strategies#
Interfaces and concrete implementations handle this the standard way:
interface PaymentStrategy {
pay(amount: number): Promise<void>;
}
class CreditCardStrategy implements PaymentStrategy {
constructor(
private cardNumber: string,
private cvv: string
) {}
async pay(amount: number): Promise<void> {
console.log(`Charging $${amount} to card ${this.cardNumber}`);
// Credit card API call
await this.processCreditCard(amount);
}
private async processCreditCard(amount: number): Promise<void> {
// Implementation details
}
}
class PayPalStrategy implements PaymentStrategy {
constructor(private email: string) {}
async pay(amount: number): Promise<void> {
console.log(`Charging $${amount} via PayPal to ${this.email}`);
// PayPal API call
await this.processPayPal(amount);
}
private async processPayPal(amount: number): Promise<void> {
// Implementation details
}
}
class CryptoStrategy implements PaymentStrategy {
constructor(private walletAddress: string) {}
async pay(amount: number): Promise<void> {
console.log(`Charging $${amount} to wallet ${this.walletAddress}`);
// Crypto payment processing
await this.processCrypto(amount);
}
private async processCrypto(amount: number): Promise<void> {
// Implementation details
}
}
// Context class uses strategy
class PaymentProcessor {
constructor(private strategy: PaymentStrategy) {}
setStrategy(strategy: PaymentStrategy): void {
this.strategy = strategy;
}
async processPayment(amount: number): Promise<void> {
await this.strategy.pay(amount);
}
}
// Usage
const processor = new PaymentProcessor(
new CreditCardStrategy('4111-1111-1111-1111', '123')
);
await processor.processPayment(100);
processor.setStrategy(new PayPalStrategy('user@example.com'));
await processor.processPayment(50);
Three classes for three payment methods, none holding more than a constructor and a pay method, is a lot of ceremony for what a function could do directly.
Functions as Strategies#
JavaScript/TypeScript has first-class functions. Strategies can be simple functions:
type PaymentStrategy = (amount: number) => Promise<void>;
const creditCardPayment: PaymentStrategy = async (amount) => {
console.log(`Charging $${amount} to credit card`);
// Credit card processing
};
const paypalPayment: PaymentStrategy = async (amount) => {
console.log(`Charging $${amount} via PayPal`);
// PayPal processing
};
const cryptoPayment: PaymentStrategy = async (amount) => {
console.log(`Charging $${amount} with crypto`);
// Crypto processing
};
// Context accepts function
class PaymentProcessor {
constructor(private strategy: PaymentStrategy) {}
setStrategy(strategy: PaymentStrategy): void {
this.strategy = strategy;
}
async processPayment(amount: number): Promise<void> {
await this.strategy(amount);
}
}
// Even simpler: no class needed
async function processPayment(
amount: number,
strategy: PaymentStrategy
): Promise<void> {
await strategy(amount);
}
// Usage
await processPayment(100, creditCardPayment);
await processPayment(50, paypalPayment);
Function strategies drop the class boilerplate. Mocking a function is simpler than mocking a class, and higher-order functions compose them directly.
When a strategy needs configuration such as card details, a factory function can return a PaymentStrategy that captures them in a closure. The processor still receives a plain function, and the captured details stay private to it.
Form Validation With Composed Strategies#
Form validation benefits from composable strategy pattern:
type ValidationStrategy = (value: string) => string | null;
// Individual validation strategies
const required: ValidationStrategy = (value) => {
return value.trim() ? null : 'This field is required';
};
const email: ValidationStrategy = (value) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(value) ? null : 'Invalid email address';
};
const minLength = (min: number): ValidationStrategy => (value) => {
return value.length >= min
? null
: `Must be at least ${min} characters`;
};
const maxLength = (max: number): ValidationStrategy => (value) => {
return value.length <= max
? null
: `Must be at most ${max} characters`;
};
const phone: ValidationStrategy = (value) => {
const phoneRegex = /^\d{10}$/;
return phoneRegex.test(value) ? null : 'Invalid phone number';
};
// Compose multiple strategies
function composeValidations(...strategies: ValidationStrategy[]): ValidationStrategy {
return (value: string) => {
for (const strategy of strategies) {
const error = strategy(value);
if (error) return error;
}
return null;
};
}
// Field configurations with composed strategies
interface FieldConfig {
name: string;
label: string;
validate: ValidationStrategy;
}
const formConfig: FieldConfig[] = [
{
name: 'email',
label: 'Email Address',
validate: composeValidations(required, email)
},
{
name: 'password',
label: 'Password',
validate: composeValidations(
required,
minLength(8),
maxLength(128)
)
},
{
name: 'phone',
label: 'Phone Number',
validate: composeValidations(required, phone)
}
];
// Form component uses strategies
function RegistrationForm() {
const [values, setValues] = useState<Record<string, string>>({});
const [errors, setErrors] = useState<Record<string, string>>({});
const handleChange = (name: string, value: string) => {
setValues(prev => ({ ...prev, [name]: value }));
// Validate using strategy
const field = formConfig.find(f => f.name === name);
if (field) {
const error = field.validate(value);
setErrors(prev => ({ ...prev, [name]: error || '' }));
}
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
// Validate all fields
const newErrors: Record<string, string> = {};
formConfig.forEach(field => {
const error = field.validate(values[field.name] || '');
if (error) newErrors[field.name] = error;
});
if (Object.keys(newErrors).length > 0) {
setErrors(newErrors);
return;
}
// Submit form
console.log('Form valid:', values);
};
return (
<form onSubmit={handleSubmit}>
{formConfig.map(field => (
<div key={field.name}>
<label>{field.label}</label>
<input
value={values[field.name] || ''}
onChange={(e) => handleChange(field.name, e.target.value)}
/>
{errors[field.name] && (
<span className="error">{errors[field.name]}</span>
)}
</div>
))}
<button type="submit">Register</button>
</form>
);
}
The composition function is the only new abstraction here. Validators stay reusable across forms, each one tests on its own, and the field configuration reads as a declarative list of rules.
Strategy pattern makes sense when algorithm selection happens at runtime, several implementations share the same interface, behavior changes with configuration, or tests need to swap implementations. Skip it when only one implementation exists, the logic is a simple conditional that reads fine as if, or the functions resist being abstracted into a common shape.
Encapsulating Undo, Redo, and Redux Actions#
Wrapping a request as an object, the core idea behind Command pattern, is what makes parameterization, queuing, logging, and undo possible. Redux actions, undo/redo stacks, and task queues all lean on it, whether or not anyone calls it by that name.
Command Objects With Execute and Undo#
Command objects with execute() and undo() methods are the standard shape:
interface Command {
execute(): void;
undo(): void;
}
class TodoList {
private todos: string[] = [];
add(todo: string): void {
this.todos.push(todo);
}
insert(index: number, todo: string): void {
this.todos.splice(index, 0, todo);
}
remove(index: number): string {
const [removed] = this.todos.splice(index, 1);
return removed;
}
getTodos(): string[] {
return [...this.todos];
}
}
class AddTodoCommand implements Command {
private index: number = -1;
constructor(
private todoList: TodoList,
private todo: string
) {}
execute(): void {
this.todoList.add(this.todo);
this.index = this.todoList.getTodos().length - 1;
}
undo(): void {
if (this.index !== -1) {
this.todoList.remove(this.index);
}
}
}
class RemoveTodoCommand implements Command {
private removedTodo: string | null = null;
constructor(
private todoList: TodoList,
private index: number
) {}
execute(): void {
this.removedTodo = this.todoList.remove(this.index);
}
undo(): void {
if (this.removedTodo !== null) {
// Put the item back where it was, not at the end
this.todoList.insert(this.index, this.removedTodo);
}
}
}
// Command history for undo/redo
class CommandHistory {
private history: Command[] = [];
private current: number = -1;
execute(command: Command): void {
// Execute command
command.execute();
// Remove any commands after current position
this.history = this.history.slice(0, this.current + 1);
// Add command to history
this.history.push(command);
this.current++;
}
undo(): void {
if (this.canUndo()) {
this.history[this.current].undo();
this.current--;
}
}
redo(): void {
if (this.canRedo()) {
this.current++;
this.history[this.current].execute();
}
}
canUndo(): boolean {
return this.current >= 0;
}
canRedo(): boolean {
return this.current < this.history.length - 1;
}
}
// Usage
const todoList = new TodoList();
const history = new CommandHistory();
history.execute(new AddTodoCommand(todoList, 'Buy milk'));
history.execute(new AddTodoCommand(todoList, 'Walk dog'));
console.log(todoList.getTodos()); // ['Buy milk', 'Walk dog']
history.undo();
console.log(todoList.getTodos()); // ['Buy milk']
history.redo();
console.log(todoList.getTodos()); // ['Buy milk', 'Walk dog']
RemoveTodoCommand records the removed item and puts it back at the same index through TodoList.insert. An undo that appended the item to the end would leave the list in a different order, and every later command that stored an index would then act on the wrong item. The natural test for a command follows from its definition: execute it, undo it, and compare the state with a snapshot taken before:
import assert from 'node:assert/strict';
const list = new TodoList();
const log = new CommandHistory();
log.execute(new AddTodoCommand(list, 'Buy milk'));
log.execute(new AddTodoCommand(list, 'Walk dog'));
log.execute(new AddTodoCommand(list, 'Pay rent'));
const before = list.getTodos();
log.execute(new RemoveTodoCommand(list, 1));
assert.deepEqual(list.getTodos(), ['Buy milk', 'Pay rent']);
log.undo();
assert.deepEqual(list.getTodos(), before);
// A redo/undo round trip must land on the same state
log.redo();
log.undo();
assert.deepEqual(list.getTodos(), before);
Grouping several edits into one undo step, such as a paste that replaces a selection, uses the same interface one level up: a composite command runs its children in order and undoes them in reverse.
Redux Actions as Commands#
Redux actions are command objects. They encapsulate state changes as serializable data:
// Action types (command types)
interface AddTodoAction {
type: 'ADD_TODO';
payload: {
id: string;
text: string;
};
}
interface RemoveTodoAction {
type: 'REMOVE_TODO';
payload: {
id: string;
};
}
interface ToggleTodoAction {
type: 'TOGGLE_TODO';
payload: {
id: string;
};
}
type TodoAction = AddTodoAction | RemoveTodoAction | ToggleTodoAction;
// Action creators (command factories)
function addTodo(text: string): AddTodoAction {
return {
type: 'ADD_TODO',
payload: {
id: crypto.randomUUID(), // Note: crypto.randomUUID() requires HTTPS or localhost
text
}
};
}
function removeTodo(id: string): RemoveTodoAction {
return {
type: 'REMOVE_TODO',
payload: { id }
};
}
function toggleTodo(id: string): ToggleTodoAction {
return {
type: 'TOGGLE_TODO',
payload: { id }
};
}
// Reducer (command handler)
interface TodoState {
todos: Array<{ id: string; text: string; completed: boolean }>;
}
function todoReducer(
state: TodoState = { todos: [] },
action: TodoAction
): TodoState {
switch (action.type) {
case 'ADD_TODO':
return {
...state,
todos: [
...state.todos,
{
id: action.payload.id,
text: action.payload.text,
completed: false
}
]
};
case 'REMOVE_TODO':
return {
...state,
todos: state.todos.filter(todo => todo.id !== action.payload.id)
};
case 'TOGGLE_TODO':
return {
...state,
todos: state.todos.map(todo =>
todo.id === action.payload.id
? { ...todo, completed: !todo.completed }
: todo
)
};
default:
return state;
}
}
// Store (command executor)
import { configureStore } from '@reduxjs/toolkit';
const store = configureStore({
reducer: todoReducer
});
// Dispatch commands
store.dispatch(addTodo('Buy milk'));
store.dispatch(addTodo('Walk dog'));
store.dispatch(toggleTodo(/* id */));
Structuring actions this way has several effects at once: the plain-object shape means they can be logged or stored, replayed for time-travel debugging, intercepted and transformed by middleware, and stored as history for undo and redo.
Intercepting Commands With Middleware#
Middleware intercepts commands before they reach reducers:
import { isAction, type Middleware } from 'redux';
// Logging middleware
const logger: Middleware = store => next => action => {
console.log('Dispatching:', action);
const result = next(action);
console.log('Next state:', store.getState());
return result;
};
// Analytics middleware
const analytics: Middleware = () => next => action => {
// Redux 5 types `action` as unknown: narrow it before reading fields
if (isAction(action) && action.type.startsWith('USER_')) {
trackEvent(action.type);
}
return next(action);
};
// Error handling middleware
const errorHandler: Middleware = store => next => action => {
try {
return next(action);
} catch (error) {
console.error('Action error:', error);
store.dispatch({
type: 'ERROR_OCCURRED',
payload: { error: error instanceof Error ? error.message : String(error) }
});
}
};
// Apply middleware with Redux Toolkit
import { configureStore } from '@reduxjs/toolkit';
const store = configureStore({
reducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(logger, analytics, errorHandler)
});
Async commands run through the thunk middleware, which configureStore adds by default. createAsyncThunk wraps one request in a command with three lifecycle actions (pending, fulfilled, and rejected), so the reducer handles each outcome as data:
import { configureStore, createAsyncThunk, createSlice } from '@reduxjs/toolkit';
interface User {
id: string;
name: string;
}
// Async command: dispatches users/fetchById/pending, then fulfilled or rejected
export const fetchUser = createAsyncThunk<User, string, { rejectValue: string }>(
'users/fetchById',
async (userId, { rejectWithValue }) => {
try {
const response = await fetch(`/api/users/${userId}`);
// fetch resolves on 404 and 500 too, so check the status explicitly
if (!response.ok) {
return rejectWithValue(`HTTP ${response.status}`);
}
return (await response.json()) as User;
} catch (error) {
// Under strict mode the catch variable is unknown: narrow it first
return rejectWithValue(error instanceof Error ? error.message : 'Network error');
}
}
);
interface UserState {
user: User | null;
status: 'idle' | 'loading' | 'succeeded' | 'failed';
error: string | null;
}
const userSlice = createSlice({
name: 'user',
initialState: { user: null, status: 'idle', error: null } as UserState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchUser.pending, (state) => {
state.status = 'loading';
state.error = null;
})
.addCase(fetchUser.fulfilled, (state, action) => {
state.status = 'succeeded';
state.user = action.payload;
})
.addCase(fetchUser.rejected, (state, action) => {
state.status = 'failed';
state.error = action.payload ?? action.error.message ?? 'Unknown error';
});
}
});
// Register the slice so its extraReducers run, then dispatch the async command
const store = configureStore({ reducer: { user: userSlice.reducer } });
store.dispatch(fetchUser('123'));
Undo/redo, queued or scheduled operations, logging and auditing, macro recording, and transaction support all call for Command. Simple CRUD without undo needs none of it, and real-time collaboration is better served by CRDTs.
State Machines Over Boolean Flags#
State pattern lets an object’s behavior shift with its internal state, which in UI code means impossible state combinations disappear and transitions stop being implicit.
Boolean State Hell#
Complex UI often leads to multiple boolean flags:
function Form() {
const [isValidating, setIsValidating] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [hasError, setHasError] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
// What if isSubmitting && hasError are both true?
// What if isSuccess && isValidating are both true?
// Many impossible combinations possible
}
Boolean states like these make impossible combinations possible: isSubmitting and isSuccess can both be true. Transitions stay unclear too, since nothing in the code says how validating becomes submitting, and testing turns into a combinatorial explosion.
Discriminated Unions as State Pattern#
TypeScript discriminated unions prevent impossible states:
type FormState =
| { status: 'idle' }
| { status: 'validating' }
| { status: 'submitting'; progress: number }
| { status: 'success'; data: SubmitResult }
| { status: 'error'; error: Error };
function Form() {
const [state, setState] = useState<FormState>({ status: 'idle' });
const handleSubmit = async () => {
// Transition to validating
setState({ status: 'validating' });
try {
await validateForm();
// Transition to submitting
setState({ status: 'submitting', progress: 0 });
const result = await submitForm((progress) => {
setState({ status: 'submitting', progress });
});
// Transition to success
setState({ status: 'success', data: result });
} catch (error) {
// Transition to error
setState({ status: 'error', error });
}
};
// Render based on state
switch (state.status) {
case 'idle':
return <FormFields onSubmit={handleSubmit} />;
case 'validating':
return <Spinner message="Validating..." />;
case 'submitting':
return <ProgressBar progress={state.progress} />;
case 'success':
return <SuccessMessage data={state.data} />;
case 'error':
return (
<>
<ErrorMessage error={state.error} />
<button onClick={handleSubmit}>Retry</button>
</>
);
}
}
Discriminated unions rule out impossible states outright (the type can’t be validating and success simultaneously), let TypeScript enforce that every state gets handled, keep transitions explicit, and attach only the data relevant to each state (progress only when submitting).
Explicit State Machines with XState#
XState provides declarative state machine definition:
import { setup, fromPromise, assign } from 'xstate';
// XState v5 declares actor logic and types up front with setup()
const formMachine = setup({
types: {
context: {} as {
formData: { success: boolean } | null;
error: unknown;
},
events: {} as
| { type: 'SUBMIT' }
| { type: 'RETRY' }
| { type: 'CANCEL' }
},
actors: {
validateForm: fromPromise(async () => {
// Validation logic
await new Promise(resolve => setTimeout(resolve, 1000));
}),
submitForm: fromPromise(async () => {
// Submission logic
await new Promise(resolve => setTimeout(resolve, 2000));
return { success: true };
})
}
}).createMachine({
id: 'form',
initial: 'idle',
context: {
formData: null,
error: null
},
states: {
idle: {
on: {
SUBMIT: 'validating'
}
},
validating: {
invoke: {
src: 'validateForm',
onDone: {
target: 'submitting'
},
onError: {
target: 'error',
actions: assign({ error: ({ event }) => event.error })
}
}
},
submitting: {
invoke: {
src: 'submitForm',
onDone: {
target: 'success',
actions: assign({ formData: ({ event }) => event.output })
},
onError: {
target: 'error',
actions: assign({ error: ({ event }) => event.error })
}
}
},
success: {
type: 'final'
},
error: {
on: {
RETRY: 'validating',
CANCEL: 'idle'
}
}
}
});
// Use in React
import { useMachine } from '@xstate/react';
function Form() {
const [state, send] = useMachine(formMachine);
return (
<form onSubmit={(e) => {
e.preventDefault();
send({ type: 'SUBMIT' });
}}>
{state.matches('idle') && (
<div>
<input name="email" />
<button type="submit">Submit</button>
</div>
)}
{state.matches('validating') && (
<Spinner message="Validating form..." />
)}
{state.matches('submitting') && (
<Spinner message="Submitting..." />
)}
{state.matches('success') && (
<SuccessMessage data={state.context.formData} />
)}
{state.matches('error') && (
<div>
<ErrorMessage error={state.context.error} />
<button onClick={() => send({ type: 'RETRY' })}>Retry</button>
<button onClick={() => send({ type: 'CANCEL' })}>Cancel</button>
</div>
)}
</form>
);
}
Visualizing State Machines#
Compared to the discriminated union above, the explicit machine adds:
- Visual design: Design state machine visually, generate code
- Impossible transitions prevented: Can’t go from
idletosuccess - Test generation: Generate tests from state machine
- Actor model: State machines can spawn and communicate
- History states: Remember previous state when returning
Wizard Steps as Machine States#
Multi-step forms benefit from explicit state machines:
import { setup, fromPromise, assign } from 'xstate';
interface WizardContext {
step1Data: any;
step2Data: any;
step3Data: any;
error: string | null;
}
type WizardEvent =
| { type: 'NEXT'; data: any }
| { type: 'PREVIOUS' }
| { type: 'SUBMIT' }
| { type: 'RESET' };
// XState v5 with setup()
const wizardMachine = setup({
types: {
context: {} as WizardContext,
events: {} as WizardEvent
},
actors: {
// Actor logic receives its data through `input`
submitWizard: fromPromise(async ({ input }: { input: WizardContext }) => {
const response = await fetch('/api/wizard', {
method: 'POST',
body: JSON.stringify({
step1: input.step1Data,
step2: input.step2Data,
step3: input.step3Data
})
});
if (!response.ok) {
throw new Error('Submission failed');
}
return response.json();
})
}
}).createMachine({
id: 'wizard',
initial: 'step1',
context: {
step1Data: null,
step2Data: null,
step3Data: null,
error: null
},
states: {
step1: {
on: {
NEXT: {
target: 'step2',
actions: assign({
step1Data: ({ event }) => event.data
})
}
}
},
step2: {
on: {
NEXT: {
target: 'step3',
actions: assign({
step2Data: ({ event }) => event.data
})
},
PREVIOUS: 'step1'
}
},
step3: {
on: {
PREVIOUS: 'step2',
SUBMIT: 'submitting'
}
},
submitting: {
invoke: {
src: 'submitWizard',
input: ({ context }) => context,
onDone: 'success',
onError: {
target: 'step3',
actions: assign({
error: ({ event }) => (event.error as Error).message
})
}
}
},
success: {
type: 'final'
}
}
});
// React component
function Wizard() {
const [state, send] = useMachine(wizardMachine);
const handleNext = (data: any) => {
send({ type: 'NEXT', data });
};
const handlePrevious = () => {
send({ type: 'PREVIOUS' });
};
const handleSubmit = () => {
send({ type: 'SUBMIT' });
};
return (
<div>
{state.matches('step1') && (
<Step1 onNext={handleNext} />
)}
{state.matches('step2') && (
<Step2
initialData={state.context.step1Data}
onNext={handleNext}
onPrevious={handlePrevious}
/>
)}
{state.matches('step3') && (
<Step3
data={{
step1: state.context.step1Data,
step2: state.context.step2Data
}}
error={state.context.error}
onSubmit={handleSubmit}
onPrevious={handlePrevious}
/>
)}
{state.matches('submitting') && (
<Spinner message="Submitting wizard..." />
)}
{state.matches('success') && (
<SuccessMessage message="Wizard completed!" />
)}
</div>
);
}
Skip state machines for simple forms with two or three states, when the team is unfamiliar with them, or when a discriminated union already rules out the same impossible combinations. Reach for them once a workflow accumulates enough states that transitions carry business rules worth reviewing visually, or once testing those transitions directly becomes critical.
Decoupling Components with a Mediator#
Mediator pattern moves the coordination rules between a set of components into one object, so the components stop referencing each other. Event buses, React Context, and Redux are often filed under Mediator too. They remove the direct references, but whether the rules end up in one place depends on how they are used.
Tight Coupling Without a Mediator#
Without mediator, components reference each other directly:
class UserList {
constructor(private userDetails: UserDetails) {}
selectUser(user: User): void {
// Direct dependency on UserDetails
this.userDetails.display(user);
}
}
class UserDetails {
display(user: User): void {
// Display user details
}
}
// Hard to test UserList without UserDetails
// Hard to reuse UserList with different detail component
An Event Bus for Decoupling#
An event bus removes the direct reference. A typed event map keeps each event name tied to its payload, so a wrong payload fails at compile time:
interface User {
id: string;
name: string;
}
// Event name -> payload type
interface AppEvents {
'user:selected': User;
'user:deselected': { id: string };
}
type Handler<T> = (payload: T) => void;
class EventBus<Events> {
private handlers: { [K in keyof Events]?: Handler<Events[K]>[] } = {};
subscribe<K extends keyof Events>(event: K, handler: Handler<Events[K]>): () => void {
const list = (this.handlers[event] ??= []);
list.push(handler);
// Return unsubscribe function
return () => {
const index = list.indexOf(handler);
if (index !== -1) {
list.splice(index, 1);
}
};
}
publish<K extends keyof Events>(event: K, payload: Events[K]): void {
// Iterate over a copy: a handler that unsubscribes itself must not
// shift the array under the loop and skip the next handler
for (const handler of [...(this.handlers[event] ?? [])]) {
handler(payload);
}
}
}
// Components communicate through the bus
class UserList {
constructor(private eventBus: EventBus<AppEvents>) {}
selectUser(user: User): void {
// Publish event instead of direct call
this.eventBus.publish('user:selected', user);
}
}
class UserDetails {
private readonly unsubscribe: () => void;
constructor(eventBus: EventBus<AppEvents>) {
// Keep the unsubscribe function: dropping it leaks the handler
this.unsubscribe = eventBus.subscribe('user:selected', user => this.display(user));
}
display(user: User): void {
console.log('Displaying user:', user.name);
}
destroy(): void {
this.unsubscribe();
}
}
class UserStats {
private readonly unsubscribe: () => void;
constructor(eventBus: EventBus<AppEvents>) {
this.unsubscribe = eventBus.subscribe('user:selected', user => this.loadStats(user));
}
loadStats(user: User): void {
console.log('Loading stats for:', user.id);
}
destroy(): void {
this.unsubscribe();
}
}
// Usage
const eventBus = new EventBus<AppEvents>();
const userList = new UserList(eventBus);
const userDetails = new UserDetails(eventBus);
const userStats = new UserStats(eventBus);
// Components don't know about each other
userList.selectUser({ id: '1', name: 'John' });
// eventBus.publish('user:selected', { id: '1' }); // Compile error: name is missing
// On teardown, each component removes its own handler
userDetails.destroy();
userStats.destroy();
The bus is publish-subscribe, a variant of Observer. It decides nothing: each subscriber carries its own reaction, so the logic stays spread across the components. That works when components only need to hear about each other. As refactoring.guru puts it, “The difference between Mediator and Observer is often elusive.” A practical test is to ask where a cross-component rule lives, such as a change in field A that disables field B and revalidates field C.
A Form Mediator That Owns the Rules#
A Mediator in the GoF sense holds that rule. Fields report their changes to one object, and that object decides what happens to the other fields. A sign-up form where a business account enables two extra fields and requires a VAT ID shows the shape:
type FieldName = 'accountType' | 'companyName' | 'vatId';
interface FieldState {
value: string;
enabled: boolean;
error: string | null;
}
class SignupFormMediator {
readonly fields: Record<FieldName, FieldState> = {
accountType: { value: 'personal', enabled: true, error: null },
companyName: { value: '', enabled: false, error: null },
vatId: { value: '', enabled: false, error: null }
};
// Fields report changes here and never reference each other
change(name: FieldName, value: string): void {
this.fields[name].value = value;
this.coordinate();
}
// Every cross-field rule lives in this one method
private coordinate(): void {
const { accountType, companyName, vatId } = this.fields;
const isBusiness = accountType.value === 'business';
companyName.enabled = isBusiness;
vatId.enabled = isBusiness;
vatId.error =
isBusiness && vatId.value.trim() === ''
? 'VAT ID is required for business accounts'
: null;
}
}
// Usage
const form = new SignupFormMediator();
form.change('accountType', 'business');
console.log(form.fields.vatId);
// { value: '', enabled: true, error: 'VAT ID is required for business accounts' }
form.change('vatId', 'DE123456789');
console.log(form.fields.vatId.error); // null
The fields stay simple: they hold a value and report changes. Adding a rule, such as clearing the company name when the account type switches back, means editing coordinate() and nothing else. The cost is that the mediator grows with every rule, so it fits a bounded group of components (one form, one dialog, one checkout step) and turns into a god object when it coordinates a whole application.
Sharing State Through React Context#
React Context provides mediator pattern for component trees:
interface AppContextValue {
selectedUser: User | null;
setSelectedUser: (user: User | null) => void;
notifications: Notification[];
addNotification: (notification: Notification) => void;
}
const AppContext = createContext<AppContextValue>(null!);
function AppProvider({ children }: { children: ReactNode }) {
const [selectedUser, setSelectedUser] = useState<User | null>(null);
const [notifications, setNotifications] = useState<Notification[]>([]);
const addNotification = (notification: Notification) => {
setNotifications(prev => [...prev, notification]);
};
return (
<AppContext.Provider value={{
selectedUser,
setSelectedUser,
notifications,
addNotification
}}>
{children}
</AppContext.Provider>
);
}
// Components communicate through context
function UserList() {
const { setSelectedUser } = useContext(AppContext);
const users = useUsers();
return (
<ul>
{users.map(user => (
<li key={user.id} onClick={() => setSelectedUser(user)}>
{user.name}
</li>
))}
</ul>
);
}
function UserDetails() {
const { selectedUser } = useContext(AppContext);
if (!selectedUser) {
return <div>Select a user</div>;
}
return (
<div>
<h2>{selectedUser.name}</h2>
<p>{selectedUser.email}</p>
</div>
);
}
function UserStats() {
const { selectedUser } = useContext(AppContext);
if (!selectedUser) return null;
return <div>Stats for {selectedUser.name}</div>;
}
// App structure
function App() {
return (
<AppProvider>
<UserList />
<UserDetails />
<UserStats />
</AppProvider>
);
}
Redux applies the same idea at application scope. Components dispatch actions instead of calling each other, and the reducers, middleware, and thunks from the Command section decide what each action changes.
Direct communication stays simplest when only two or three components are involved: skip Mediator if parent-child props already work, since the added indirection only makes debugging harder without buying anything back. Past that scale, the right tool depends on reach. An event bus covers same-module pub/sub in a prototype with no global-state requirement, and React Context covers a single subtree once prop drilling for theme, auth, or locale gets painful. A mediator object fits when a bounded group of components shares rules that need one home, such as the field dependencies of a form. Redux earns its weight in large applications where many components read the same state, DevTools and time-travel debugging matter, and the team already knows the middleware ecosystem.
Language Feature or Library#
The language-first default holds for most application code, where nothing forces a dependency and nobody joining the codebase needs a library explained first. Override it when the escalation buys a capability you would otherwise hand-roll badly.
Related Posts#
- Creational Patterns in Modern TypeScript - Part 1 of this series
- Structural Patterns Meet Component Composition - Part 2 of this series
References#
- Behavioral Design Patterns (opens in new tab) - refactoring.guru catalog of Observer, Strategy, Command, State, and Mediator patterns
- RxJS Documentation (opens in new tab) - Official reactive programming library for JavaScript
- ReactiveX - Observable (opens in new tab) - Cross-language Observable specification and operator reference
- XState Documentation (opens in new tab) - XState v5 reference for
setup(), actor logic, andassignused in the state machine examples - Redux Toolkit (opens in new tab) - Official Redux toolset covering
configureStore,createSlice, and middleware setup - Design Patterns: Elements of Reusable Object-Oriented Software (opens in new tab) - Original GoF book defining the 23 classic patterns
- Mediator (opens in new tab) - refactoring.guru page on Mediator, including how it differs from an Observer-based setup with no central coordinator
- RxJS share (opens in new tab) -
share()reference: the source subscription is dropped and reset once the subscriber count reaches zero - RxJS repeat (opens in new tab) -
repeat({ delay })resubscribes on completion and does not catch errors, which is whatretryis for - Node.js Events: events.on() (opens in new tab) - Async iterator over events with
AbortSignalcancellation and listener removal on loop exit - MDN: Window.fetch() (opens in new tab) -
fetch()does not reject on HTTP error statuses such as 404, soResponse.okneeds an explicit check - TypeScript: useUnknownInCatchVariables (opens in new tab) - Compiler option that types catch clause variables as
unknown, part of thestrictfamily - Migrating to RTK 2.0 and Redux 5.0 (opens in new tab) -
AnyActiondeprecated in favor ofUnknownAction; middlewareactiontyped asunknownand narrowed withisAction - createAsyncThunk (opens in new tab) - Redux Toolkit API that dispatches pending, fulfilled, and rejected actions, with
rejectWithValuefor typed failures - React-Redux Hooks (opens in new tab) -
useSelectorsubscription and===re-render rule; hooks recommended as the default overconnect
Modern Perspective on Classic Design Patterns
Part 3 of 4A comprehensive series examining how classic Gang of Four design patterns have evolved in modern TypeScript, React, and functional programming contexts. Learn when classic patterns still apply, when they've been superseded, and how to recognize underlying principles in modern codebases.
All posts in this series
Related posts
Match architecture weight to the requests each init serves: lean handlers where Lambda traffic is sparse, light DI on a Lambdalith, full OOP/DI on long-lived runtimes.
architecture · lambda · serverless +3
A practical guide to learning Effect incrementally and integrating it with AWS Lambda, with real code examples, common pitfalls, and production patterns.
typescript · functional-programming · lambda +4
A small, complete URL shortener on AWS Lambda and DynamoDB with Effect and SST v4, showing schema-at-the-boundary, layers, and tagged-error mapping.
functional-programming · lambda · typescript +2
A pragmatic guide for designers working with async backends: three interaction patterns, when to use each, and four anti-patterns to push back against.
event-driven · state-management · design-patterns +2
How SOLID principles apply to modern JavaScript: practical examples with TypeScript, React hooks, and functional patterns, plus when they're overkill.
typescript · javascript · react +4