JavaScript and TypeScript course ยท Module 9: Design Patterns and Architecture
State Management Patterns in JavaScript/TypeScript
In this lesson5
In the park's control room the state changes every second: open gates, fed dinosaurs, alarms. When every module changes this data in its own way, after a failure nobody knows who opened the Velociraptor paddock gate, or when. State management patterns help here, and you will learn three of them: Flux, Event Sourcing and State Machines.
Flux Architecture - Unidirectional data flow
Flux is an application architecture pattern that introduces a unidirectional data flow, which makes the application state more predictable and easier to debug. It was proposed by Facebook: an action goes to the dispatcher, the dispatcher passes it to the stores, and the view refreshes after the change.
Basic Flux components
An action (Action) is an object with a type field and an optional payload, the dispatcher distributes actions, the store holds the state and notifies subscribers, and action creators are functions that create actions:
// Types for Flux
type Action<T = any> = {
type: string;
payload?: T;
};
type Listener = () => void;
// Store - holds application state
class Store<T> {
private state: T;
private listeners: Listener[] = [];
constructor(initialState: T) {
this.state = initialState;
}
getState(): T {
return this.state;
}
protected setState(newState: T): void {
this.state = newState;
this.emitChange();
}
subscribe(listener: Listener): () => void {
this.listeners.push(listener);
// Return unsubscribe function
return () => {
const index = this.listeners.indexOf(listener);
if (index > -1) {
this.listeners.splice(index, 1);
}
};
}
private emitChange(): void {
this.listeners.forEach(listener => listener());
}
}
// Dispatcher - central hub for all actions
class Dispatcher {
private callbacks: Array<(action: Action) => void> = [];
register(callback: (action: Action) => void): string {
const id = Math.random().toString(36).slice(2, 11);
this.callbacks.push(callback);
return id;
}
dispatch(action: Action): void {
console.log('Dispatching action:', action);
this.callbacks.forEach(callback => {
callback(action);
});
}
}
// Action Creators - functions that create actions
const TodoActions = {
addTodo: (text: string): Action<{ text: string }> => ({
type: 'ADD_TODO',
payload: { text }
}),
toggleTodo: (id: string): Action<{ id: string }> => ({
type: 'TOGGLE_TODO',
payload: { id }
}),
deleteTodo: (id: string): Action<{ id: string }> => ({
type: 'DELETE_TODO',
payload: { id }
}),
setFilter: (filter: 'all' | 'active' | 'completed'): Action<{ filter: string }> => ({
type: 'SET_FILTER',
payload: { filter }
})
};
// Application state
interface Todo {
id: string;
text: string;
completed: boolean;
createdAt: Date;
}
interface TodoState {
todos: Todo[];
filter: 'all' | 'active' | 'completed';
}
// TodoStore implementation
class TodoStore extends Store<TodoState> {
constructor(dispatcher: Dispatcher) {
super({
todos: [],
filter: 'all'
});
// Register with dispatcher
dispatcher.register((action: Action) => {
this.handleAction(action);
});
}
private handleAction(action: Action): void {
const currentState = this.getState();
switch (action.type) {
case 'ADD_TODO':
this.setState({
...currentState,
todos: [
...currentState.todos,
{
id: Math.random().toString(36).slice(2, 11),
text: action.payload.text,
completed: false,
createdAt: new Date()
}
]
});
break;
case 'TOGGLE_TODO':
this.setState({
...currentState,
todos: currentState.todos.map(todo =>
todo.id === action.payload.id
? { ...todo, completed: !todo.completed }
: todo
)
});
break;
case 'DELETE_TODO':
this.setState({
...currentState,
todos: currentState.todos.filter(todo => todo.id !== action.payload.id)
});
break;
case 'SET_FILTER':
this.setState({
...currentState,
filter: action.payload.filter
});
break;
case 'LOAD_TODOS_SUCCESS':
this.setState({
...currentState,
todos: action.payload.todos
});
break;
default:
// No state changes for unknown actions
break;
}
}
// Selectors - functions for retrieving processed data
getFilteredTodos(): Todo[] {
const { todos, filter } = this.getState();
switch (filter) {
case 'active':
return todos.filter(todo => !todo.completed);
case 'completed':
return todos.filter(todo => todo.completed);
default:
return todos;
}
}
getStats() {
const todos = this.getState().todos;
return {
total: todos.length,
completed: todos.filter(todo => todo.completed).length,
active: todos.filter(todo => !todo.completed).length
};
}
}
// Using Flux
const dispatcher = new Dispatcher();
const todoStore = new TodoStore(dispatcher);
// Subscribing to changes
const unsubscribe = todoStore.subscribe(() => {
console.log('State changed:', {
todos: todoStore.getFilteredTodos(),
stats: todoStore.getStats(),
filter: todoStore.getState().filter
});
});
// Executing actions
dispatcher.dispatch(TodoActions.addTodo('Learn Flux'));
dispatcher.dispatch(TodoActions.addTodo('Implement TodoApp'));
dispatcher.dispatch(TodoActions.toggleTodo(todoStore.getState().todos[0].id));
dispatcher.dispatch(TodoActions.setFilter('active'));setState is protected, so a new state can only be set by an action that went through the dispatcher. getState still returns a reference to the state object, though, through which the state can be changed without going through the dispatcher. That is why it is worth freezing the new state before the store notifies its subscribers: Object.freeze is shallow, so nested arrays such as todos get frozen too. Every element has a single responsibility (SRP), and a store usually exists as a single instance, like a Singleton. In Redux, the logic from handleAction moves into a reducer: a pure function that creates a new state from the current state and an action.
Advanced Flux with Middleware
Middleware is a layer that every action passes through before it reaches the store, like an airlock in front of a paddock. Here it adds logging, debugging and handling of asynchronous actions:
// Middleware for Flux
type Middleware = (action: Action, next: (action: Action) => void) => void;
class EnhancedDispatcher extends Dispatcher {
private middlewares: Middleware[] = [];
use(middleware: Middleware): void {
this.middlewares.push(middleware);
}
dispatch(action: Action): void {
let index = 0;
const next = (currentAction: Action) => {
if (index < this.middlewares.length) {
const middleware = this.middlewares[index++];
middleware(currentAction, next);
} else {
super.dispatch(currentAction);
}
};
next(action);
}
}
// Logging middleware
const loggingMiddleware: Middleware = (action, next) => {
console.group(`Action: ${action.type}`);
console.log('Payload:', action.payload);
console.time('Action Duration');
next(action);
console.timeEnd('Action Duration');
console.groupEnd();
};
// Debug middleware
const debugMiddleware: Middleware = (action, next) => {
if (process.env.NODE_ENV === 'development') {
console.log('Debug: Before action', action);
}
next(action);
if (process.env.NODE_ENV === 'development') {
console.log('Debug: After action', action);
}
};
// Async action handling middleware
const asyncMiddleware: Middleware = (action, next) => {
if (typeof action.payload === 'function') {
// This is an async action
action.payload((asyncAction: Action) => {
next(asyncAction);
});
} else {
next(action);
}
};
// Async Action Creator
const AsyncTodoActions = {
loadTodos: () => ({
type: 'ASYNC_ACTION',
payload: (dispatch: (action: Action) => void) => {
// API call simulation
setTimeout(() => {
dispatch({
type: 'LOAD_TODOS_SUCCESS',
payload: {
todos: [
{ id: '1', text: 'Todo from API', completed: false, createdAt: new Date() }
]
}
});
}, 1000);
}
})
};
// Using Enhanced Dispatcher
const enhancedDispatcher = new EnhancedDispatcher();
enhancedDispatcher.use(loggingMiddleware);
enhancedDispatcher.use(debugMiddleware);
enhancedDispatcher.use(asyncMiddleware);
const enhancedTodoStore = new TodoStore(enhancedDispatcher);Each middleware decides whether to call next, so it can stop, delay or enrich an action. You add new behavior with use, without editing the class, in line with the open/closed principle.
Event Sourcing - Event history as source of truth
Event Sourcing is a pattern in which the application state is determined by a sequence of events, instead of storing the current state directly. It is like a ranger's logbook: you do not overwrite the board with the paddock status, you record every event and rebuild the state by reading the log from the beginning.
Basic Event Sourcing implementation
An aggregate (Aggregate) is an object whose state we build from events, here User. Methods such as changeEmail do not change the state, they only return new events, and the change itself is made by apply:
// Types for Event Sourcing
interface Event {
id: string;
type: string;
data: any;
timestamp: Date;
version: number;
}
interface Aggregate {
id: string;
version: number;
apply(event: Event): void;
}
// Event Store - stores all events
class EventStore {
private events: Map<string, Event[]> = new Map();
async saveEvents(aggregateId: string, events: Event[], expectedVersion: number): Promise<void> {
const existingEvents = this.events.get(aggregateId) || [];
if (existingEvents.length !== expectedVersion) {
throw new Error('Concurrency conflict: unexpected version');
}
// Adding new events
const newEvents = events.map((event, index) => ({
...event,
version: expectedVersion + index + 1,
timestamp: new Date()
}));
this.events.set(aggregateId, [...existingEvents, ...newEvents]);
console.log(`Saved ${newEvents.length} events for aggregate ${aggregateId}`);
}
async getEvents(aggregateId: string, fromVersion: number = 0): Promise<Event[]> {
const events = this.events.get(aggregateId) || [];
return events.filter(event => event.version > fromVersion);
}
async getAllEvents(): Promise<Event[]> {
const allEvents: Event[] = [];
for (const events of this.events.values()) {
allEvents.push(...events);
}
return allEvents.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
}
}
// Event definitions
const UserEvents = {
UserCreated: (data: { name: string; email: string }) => ({
type: 'UserCreated',
data
}),
UserEmailChanged: (data: { email: string }) => ({
type: 'UserEmailChanged',
data
}),
UserDeactivated: (data: { reason: string }) => ({
type: 'UserDeactivated',
data
}),
UserReactivated: () => ({
type: 'UserReactivated',
data: {}
})
};
// User Aggregate
class User implements Aggregate {
id: string;
version: number = 0;
name: string = '';
email: string = '';
isActive: boolean = true;
createdAt?: Date;
deactivatedAt?: Date;
constructor(id: string) {
this.id = id;
}
// Methods for creating events (commands)
static create(id: string, name: string, email: string): { user: User; events: any[] } {
const user = new User(id);
const events = [UserEvents.UserCreated({ name, email })];
return { user, events };
}
changeEmail(newEmail: string): any[] {
if (this.email === newEmail) {
return []; // No changes
}
if (!this.isActive) {
throw new Error('Cannot change email for deactivated user');
}
return [UserEvents.UserEmailChanged({ email: newEmail })];
}
deactivate(reason: string): any[] {
if (!this.isActive) {
return []; // Already inactive
}
return [UserEvents.UserDeactivated({ reason })];
}
reactivate(): any[] {
if (this.isActive) {
return []; // Already active
}
return [UserEvents.UserReactivated()];
}
// Applying events to change state
apply(event: Event): void {
switch (event.type) {
case 'UserCreated':
this.name = event.data.name;
this.email = event.data.email;
this.createdAt = event.timestamp;
this.isActive = true;
break;
case 'UserEmailChanged':
this.email = event.data.email;
break;
case 'UserDeactivated':
this.isActive = false;
this.deactivatedAt = event.timestamp;
break;
case 'UserReactivated':
this.isActive = true;
this.deactivatedAt = undefined;
break;
default:
throw new Error(`Unknown event type: ${event.type}`);
}
this.version = event.version;
}
// Reconstructing state from events
static fromHistory(id: string, events: Event[]): User {
const user = new User(id);
events.forEach(event => user.apply(event));
return user;
}
}
// Repository for User Aggregate
class UserRepository {
constructor(private eventStore: EventStore) {}
async save(user: User, newEvents: any[]): Promise<void> {
if (newEvents.length === 0) return;
const events = newEvents.map(eventData => ({
id: Math.random().toString(36).slice(2, 11),
type: eventData.type,
data: eventData.data,
timestamp: new Date(),
version: 0 // Will be set in EventStore
}));
await this.eventStore.saveEvents(user.id, events, user.version);
// Applying the saved events (with versions assigned by the EventStore) to the aggregate
const savedEvents = await this.eventStore.getEvents(user.id, user.version);
savedEvents.forEach(event => user.apply(event));
}
async getById(id: string): Promise<User | null> {
const events = await this.eventStore.getEvents(id);
if (events.length === 0) {
return null;
}
return User.fromHistory(id, events);
}
}
// Using Event Sourcing
async function demonstrateEventSourcing() {
const eventStore = new EventStore();
const userRepository = new UserRepository(eventStore);
// Creating a user
const { user, events } = User.create('user1', 'Jan Kowalski', 'jan@example.com');
await userRepository.save(user, events);
console.log('User after creation:', user);
// Changing email
const emailChangeEvents = user.changeEmail('jan.kowalski@example.com');
await userRepository.save(user, emailChangeEvents);
console.log('User after email change:', user);
// Deactivation
const deactivateEvents = user.deactivate('User requested account deletion');
await userRepository.save(user, deactivateEvents);
console.log('User after deactivation:', user);
// Reactivation
const reactivateEvents = user.reactivate();
await userRepository.save(user, reactivateEvents);
console.log('User after reactivation:', user);
// Reconstructing state from events
const reconstructedUser = await userRepository.getById('user1');
console.log('Reconstructed user:', reconstructedUser);
// History of all events
const allEvents = await eventStore.getAllEvents();
console.log('Event history:', allEvents);
}
demonstrateEventSourcing();EventStore guards the versions: if someone added an event in the meantime, the save ends with a conflict (optimistic concurrency control). That is why the repository applies the events with the versions assigned by the store, and fromHistory rebuilds the user from the history alone.
Projectors and Read Models
Reading the whole history for every question would be slow. A projector listens to events and builds a model that is ready to read (read model) from them, for example statistics:
// Projector - creates read models from events
abstract class Projector {
abstract getProjectionName(): string;
abstract handle(event: Event): Promise<void>;
}
// Read Model for user statistics
interface UserStats {
totalUsers: number;
activeUsers: number;
deactivatedUsers: number;
emailChanges: number;
}
class UserStatsProjector extends Projector {
private stats: UserStats = {
totalUsers: 0,
activeUsers: 0,
deactivatedUsers: 0,
emailChanges: 0
};
getProjectionName(): string {
return 'UserStats';
}
async handle(event: Event): Promise<void> {
switch (event.type) {
case 'UserCreated':
this.stats.totalUsers++;
this.stats.activeUsers++;
break;
case 'UserEmailChanged':
this.stats.emailChanges++;
break;
case 'UserDeactivated':
this.stats.activeUsers--;
this.stats.deactivatedUsers++;
break;
case 'UserReactivated':
this.stats.activeUsers++;
this.stats.deactivatedUsers--;
break;
}
console.log(`[UserStatsProjector] Updated stats:`, this.stats);
}
getStats(): UserStats {
return { ...this.stats };
}
}
// Event Bus for projectors
class EventBus {
private projectors: Projector[] = [];
registerProjector(projector: Projector): void {
this.projectors.push(projector);
}
async publishEvent(event: Event): Promise<void> {
console.log(`Publishing event: ${event.type}`);
const promises = this.projectors.map(projector =>
projector.handle(event).catch(error => {
console.error(`Error in projector ${projector.getProjectionName()}:`, error);
})
);
await Promise.all(promises);
}
}
// Enhanced Event Store with Event Bus
class EnhancedEventStore extends EventStore {
constructor(private eventBus: EventBus) {
super();
}
async saveEvents(aggregateId: string, events: Event[], expectedVersion: number): Promise<void> {
await super.saveEvents(aggregateId, events, expectedVersion);
// Publishing events to projectors
const savedEvents = await this.getEvents(aggregateId, expectedVersion);
for (const event of savedEvents) {
await this.eventBus.publishEvent(event);
}
}
}
// Usage with projectors
async function demonstrateProjectors() {
const eventBus = new EventBus();
const userStatsProjector = new UserStatsProjector();
eventBus.registerProjector(userStatsProjector);
const enhancedEventStore = new EnhancedEventStore(eventBus);
const userRepository = new UserRepository(enhancedEventStore);
// Performing operations - projectors will be automatically updated
const { user, events } = User.create('user2', 'Anna Nowak', 'anna@example.com');
await userRepository.save(user, events);
const emailChangeEvents = user.changeEmail('anna.nowak@example.com');
await userRepository.save(user, emailChangeEvents);
console.log('Final statistics:', userStatsProjector.getStats());
}
demonstrateProjectors();A projector does not change the history, it only summarizes it, so you can add a new one at any moment and feed it the existing events.
State Machines with XState
State machines let you model complex state flows in a declarative and predictable way. A machine is always in exactly one state, and a transition happens only after an event that is allowed in that state, like a gate you cannot open during feeding.
Basic state machine
First, our own machine. Each state has an on map in which an event points to the next state, plus optional entry and exit hooks that run on entering and leaving:
// Simple state machine implementation (without XState)
interface StateDefinition {
on: Record<string, string>;
entry?: () => void;
exit?: () => void;
}
interface MachineConfig {
id: string;
initial: string;
states: Record<string, StateDefinition>;
}
class StateMachine {
private currentState: string;
private config: MachineConfig;
private listeners: Array<(state: string) => void> = [];
constructor(config: MachineConfig) {
this.config = config;
this.currentState = config.initial;
this.executeEntry();
}
getCurrentState(): string {
return this.currentState;
}
send(event: string): void {
const currentStateConfig = this.config.states[this.currentState];
const nextState = currentStateConfig.on[event];
if (!nextState) {
console.warn(`Event "${event}" not handled in state "${this.currentState}"`);
return;
}
this.transition(nextState);
}
private transition(nextState: string): void {
if (!this.config.states[nextState]) {
throw new Error(`State "${nextState}" not defined`);
}
console.log(`Transition: ${this.currentState} -> ${nextState}`);
// Exit current state
this.executeExit();
// Change state
const previousState = this.currentState;
this.currentState = nextState;
// Entry new state
this.executeEntry();
// Notify listeners
this.listeners.forEach(listener => listener(this.currentState));
}
private executeEntry(): void {
const stateConfig = this.config.states[this.currentState];
if (stateConfig.entry) {
stateConfig.entry();
}
}
private executeExit(): void {
const stateConfig = this.config.states[this.currentState];
if (stateConfig.exit) {
stateConfig.exit();
}
}
subscribe(listener: (state: string) => void): () => void {
this.listeners.push(listener);
return () => {
const index = this.listeners.indexOf(listener);
if (index > -1) {
this.listeners.splice(index, 1);
}
};
}
}
// Example: State machine for order process
const orderMachine = new StateMachine({
id: 'order',
initial: 'cart',
states: {
cart: {
on: {
CHECKOUT: 'checkout'
},
entry: () => console.log('Entered cart state'),
exit: () => console.log('Exited cart state')
},
checkout: {
on: {
PAYMENT: 'payment',
BACK_TO_CART: 'cart'
},
entry: () => console.log('Entered checkout state')
},
payment: {
on: {
SUCCESS: 'confirmed',
FAILURE: 'payment_failed',
BACK_TO_CHECKOUT: 'checkout'
},
entry: () => console.log('Processing payment...')
},
payment_failed: {
on: {
RETRY: 'payment',
BACK_TO_CHECKOUT: 'checkout'
},
entry: () => console.log('Payment failed!')
},
confirmed: {
on: {
FULFILL: 'shipped'
},
entry: () => console.log('Order confirmed!')
},
shipped: {
on: {
DELIVER: 'delivered'
},
entry: () => console.log('Order shipped!')
},
delivered: {
on: {},
entry: () => console.log('Order delivered!')
}
}
});
// Subscribe to state changes
orderMachine.subscribe((state) => {
console.log(`Current state: ${state}`);
});
// Simulate order flow
console.log('=== Order Flow Simulation ===');
orderMachine.send('CHECKOUT');
orderMachine.send('PAYMENT');
orderMachine.send('SUCCESS');
orderMachine.send('FULFILL');
orderMachine.send('DELIVER');An event that is not allowed in the current state, for example DELIVER in the cart, is ignored with a warning, so an invalid transition is impossible.
XState integration (conceptual)
XState is a popular state machine library. It adds context (data kept next to the state), guards that block transitions, and invoking services such as a payment:
// Example of what a state machine would look like with XState
// (conceptual code - requires XState installation)
/*
import { createMachine, interpret } from 'xstate';
const orderMachineXState = createMachine({
id: 'order',
initial: 'cart',
context: {
items: [],
total: 0,
customer: null
},
states: {
cart: {
on: {
ADD_ITEM: {
actions: 'addItem'
},
REMOVE_ITEM: {
actions: 'removeItem'
},
CHECKOUT: {
target: 'checkout',
cond: 'hasItems'
}
}
},
checkout: {
entry: 'calculateTotal',
on: {
PAYMENT: 'payment',
BACK_TO_CART: 'cart'
}
},
payment: {
invoke: {
id: 'paymentService',
src: 'processPayment',
onDone: {
target: 'confirmed',
actions: 'savePaymentInfo'
},
onError: {
target: 'payment_failed',
actions: 'savePaymentError'
}
},
on: {
BACK_TO_CHECKOUT: 'checkout'
}
},
payment_failed: {
on: {
RETRY: 'payment',
BACK_TO_CHECKOUT: 'checkout'
}
},
confirmed: {
entry: 'sendConfirmationEmail',
on: {
FULFILL: 'shipped'
}
},
shipped: {
entry: 'sendShippingNotification',
on: {
DELIVER: 'delivered'
}
},
delivered: {
entry: 'sendDeliveryConfirmation',
type: 'final'
}
}
}, {
actions: {
addItem: (context, event) => {
// Add item to cart
},
removeItem: (context, event) => {
// Remove item from cart
},
calculateTotal: (context) => {
// Calculate total
},
savePaymentInfo: (context, event) => {
// Save payment info
}
},
guards: {
hasItems: (context) => context.items.length > 0
},
services: {
processPayment: (context) => {
// Returns Promise with payment process
return fetch('/api/payment', {
method: 'POST',
body: JSON.stringify(context)
});
}
}
});
*/The code is commented out because it requires installing the library, and it uses the XState 4 API. In version 5, interpret was replaced by createActor, cond is called guard, services became actors, actions and guards receive a single object ({ context, event }), and a service that returns a Promise has to be wrapped in fromPromise.
Advanced state machines with hierarchy
A machine can also hold context, like this music player with a volume and a playlist:
// Hierarchical state machine for a music player
interface PlayerContext {
currentTrack: string | null;
volume: number;
position: number;
playlist: string[];
}
class HierarchicalStateMachine extends StateMachine {
private context: any = {};
constructor(config: MachineConfig, initialContext: any = {}) {
super(config);
this.context = { ...initialContext };
}
getContext(): any {
return { ...this.context };
}
updateContext(updates: any): void {
this.context = { ...this.context, ...updates };
}
}
const musicPlayerMachine = new HierarchicalStateMachine({
id: 'musicPlayer',
initial: 'stopped',
states: {
stopped: {
on: {
PLAY: 'playing',
LOAD: 'loading'
},
entry: () => console.log('Player stopped')
},
loading: {
on: {
LOADED: 'playing',
ERROR: 'error'
},
entry: () => console.log('Loading track...')
},
playing: {
on: {
PAUSE: 'paused',
STOP: 'stopped',
NEXT: 'loading',
PREVIOUS: 'loading'
},
entry: () => console.log('Playing music'),
exit: () => console.log('Stopped playing')
},
paused: {
on: {
PLAY: 'playing',
STOP: 'stopped'
},
entry: () => console.log('Music paused')
},
error: {
on: {
RETRY: 'loading',
STOP: 'stopped'
},
entry: () => console.log('Error loading track')
}
}
}, {
currentTrack: null,
volume: 50,
position: 0,
playlist: ['track1.mp3', 'track2.mp3']
});
// Player simulation
console.log('=== Music Player Simulation ===');
musicPlayerMachine.send('LOAD');
musicPlayerMachine.send('LOADED');
musicPlayerMachine.send('PAUSE');
musicPlayerMachine.send('PLAY');
musicPlayerMachine.send('NEXT');The class name overpromises: it is still a flat machine extended with context. Real hierarchy means nested states, for example playing with the substates normal and shuffle, which XState supports natively.
Comparing state management patterns
When to use which pattern?
In a large application the patterns often work together, each responsible for a different kind of state:
// Example application using all three patterns
// 1. Flux - for simple UI state management
class UIStateManager {
// Managing UI component state, forms, modals
}
// 2. Event Sourcing - for business logic with history
class OrderEventStore {
// Managing orders with full change history
}
// 3. State Machines - for complex flows
class WorkflowStateMachine extends StateMachine {
// Managing business workflows (approval workflows, etc.)
}
// Combining patterns in one application
class ApplicationStateManager {
private uiState: UIStateManager;
private orderEvents: OrderEventStore;
private workflows: Map<string, WorkflowStateMachine>;
constructor() {
this.uiState = new UIStateManager();
this.orderEvents = new OrderEventStore();
this.workflows = new Map();
}
// Flux for UI
updateUI(action: Action): void {
// this.uiState.dispatch(action);
}
// Event Sourcing for business events
processBusinessEvent(event: Event): void {
// this.orderEvents.append(event);
}
// State Machines for workflows
advanceWorkflow(workflowId: string, event: string): void {
const workflow = this.workflows.get(workflowId);
if (workflow) {
workflow.send(event);
}
}
}Flux handles the interface state, Event Sourcing the business data with its history, and state machines the flows, such as approving an order.
Best practices
Three rules keep the work organized: separate the kinds of state, test each pattern separately and take care of performance:
// 1. Separation of Concerns
interface StatePattern {
// UI State - Flux/Redux
uiState: {
loading: boolean;
errors: string[];
notifications: any[];
};
// Business State - Event Sourcing
businessEvents: Event[];
// Workflow State - State Machines
workflows: Record<string, string>; // workflowId -> currentState
}
// 2. Testing patterns
class StatePatternTests {
testFluxActions(): void {
// Test action creators, reducers, stores
}
testEventSourcing(): void {
// Test event application, projectors
}
testStateMachines(): void {
// Test state transitions, guards, actions
}
}
// 3. Performance considerations
class PerformanceOptimizations {
// Memoization for Flux selectors
memoizedSelectors = new Map();
// Snapshotting for Event Sourcing
snapshots = new Map();
// State Machine caching
machineInstances = new Map();
}Memoizing selectors saves computation in Flux, and snapshots in Event Sourcing let you rebuild the state from the latest snapshot instead of from the very first event.
Summary of state management patterns
Flux gives you a simple unidirectional flow, easy debugging and change tracking, so it fits UI state, although in simple applications it can be over-engineering. Event Sourcing gives you the full history, rebuilding the state from any moment and natural auditing, at the cost of complexity and disk space. State machines clearly model complex flows, rule out invalid states and are easy to visualize and test, although they have a learning curve and can be overkill for simple states.
My recommendation: in a small application basic state (useState, signals) is enough, in a medium one use Flux/Redux for the UI, in a large one a combination of patterns, and in enterprise systems Event Sourcing and state machines for critical processes. In the editor below you will build the park's security system, and in the next lesson we will take on code splitting and tree shaking.
Remember: the park's state is its memory, so change it only through one well-guarded gate.
Code for this lesson: index.js
// Park Security System
// Exercise: Implement a sensor monitoring system
class SecuritySystem {
constructor() {
this.sensors = new Map();
this.alerts = [];
this.securityLevel = "GREEN";
}
// Implement the methods:
// addSensor(zone, type) - add a sensor to a zone
// triggerAlert(zone, severity) - trigger an alert
// getStatus() - return the security status
addSensor(zone, type) {
// Your code here
}
triggerAlert(zone, severity) {
// Your code here
}
getStatus() {
// Your code here
}
}
const security = new SecuritySystem();
security.addSensor("Sector A", "motion");
console.log("Security system active");Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the Single Responsibility Principle (SRP) mean?
2. What does the Open/Closed Principle mean?
Hands-on tasks in the game
- Code editor
The index.js file has a VisitorManagementSystem class that keeps visitors in a Map under their ticket number. Fill in the blanks: ___BLANK1___ is the Map method that returns the visitor for a ticket number, ___BLANK2___ is the array method that turns the list of visitors into one object with the number of people in each zone (it starts from an empty object {}), and ___BLANK3___ is the Map property with the number of stored visitors. trackVisitorLocation should return false for an unknown ticket, and getStats() should return { total, byZone }, e.g. { total: 2, byZone: { entrance: 1, raptors: 1 } }.
- Vertical ordering
Arrange the stages of Singleton pattern implementation:
- Code editor
The index.js file has a GeneticLaboratory class. Fill in the blanks: ___BLANK1___ is the regular expression method that checks whether a string matches the pattern (the sequence contains only the letters A, C, G and T) and returns true or false, ___BLANK2___ is the field of the analyzeDNA result that says whether the DNA is valid, and ___BLANK3___ is an expression that returns a new array with all species stored in the Map this.species. analyzeDNA should return { valid, length, gcContent }, synthesize must not create a species from invalid DNA (it returns null then), and getSpeciesDatabase returns an array of species.