Buses
The bus pattern provides a way to decouple different parts of your application by using message-based communication. use-less-react provides three types of buses that implement the CQRS (Command Query Responsibility Segregation) pattern and event-driven architecture:
Command Bus
The Command Bus handles commands, which represent intentions to modify state. Commands are dispatched to registered handlers that perform the actual work. This pattern separates the "what" (the command) from the "how" (the handler).
- Commands represent write operations
- Each command has a single handler
- Commands don't return values (they perform side effects)
Learn more: Command Bus
Query Bus
The Query Bus handles queries, which represent read operations. Queries are dispatched to registered handlers that return data without modifying state.
- Queries represent read operations
- Each query has a single handler
- Queries return typed results
Learn more: Query Bus
Event Bus
The Event Bus implements the publish/subscribe pattern for event-driven architectures. Events represent things that have happened in the system and can have multiple handlers.
- Events represent things that have happened
- Each event can have multiple handlers
- Events are published after state changes occur
Learn more: Event Bus
When to Use Buses
Buses are particularly useful when:
- You need to decouple different parts of your application
- You want to implement CQRS pattern (separation of read and write operations)
- You need event-driven architecture for handling side effects
- You want to add cross-cutting concerns (logging, monitoring, validation) in a centralized way
- You need to support distributed systems (with Hybrid buses)
Common Workflow
A typical workflow using all three buses:
- Command is dispatched to modify state
- Command handler performs the operation and publishes an Event
- Event handlers react to the event (send emails, update analytics, etc.)
- Query is dispatched to read the updated state
This separation ensures that your application logic is clean, testable, and maintainable.