Frontend Patterns

Pattern

Pub/Sub

Decouple components through event-based communication without direct references.

State Management Intermediate

Pub/Sub

Problem

Components that directly reference each other create tight coupling, making the codebase rigid and hard to change. When a component needs to notify others about events, passing callbacks through multiple prop layers becomes unwieldy. Adding new listeners or removing old ones requires touching code throughout the component tree, increasing the risk of breaking changes.

Solution

Decouple publishers from subscribers through a message broker that routes events. This allows components to communicate without direct references, making the system more flexible.

Example

This example demonstrates a simple publish-subscribe event bus that decouples publishers from subscribers through a centralized message broker.

const eventBus = {
  // Store callbacks organized by event name
  events: {},

  subscribe(event, callback) {
    // Register callback for specific event
    if (!this.events[event]) this.events[event] = [];
    this.events[event].push(callback);
  },

  publish(event, data) {
    // Notify all subscribers of this event
    if (this.events[event]) {
      this.events[event].forEach(cb => cb(data));
    }
  }
};

Benefits

  • Decouples publishers from subscribers, enabling independent changes.
  • Makes adding new subscribers easy without modifying existing code.
  • Enables flexible event-driven architectures with loose coupling.
  • Simplifies communication between distant or unrelated components.

Tradeoffs

  • Makes data flow implicit and harder to trace through the application.
  • Can create memory leaks if subscribers don’t properly unsubscribe.
  • Debugging is harder when trying to track which subscriber handled an event.
  • May lead to spaghetti code if overused without clear event contracts.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.