State Management Patterns
This section covers architectural techniques and practical scenarios for designing business logic with @pravosleva/reactive-engine v3.0.1.
Powered by an intrusive graph (NodeLink), object pooling (LinkPool), and O(1) cursor-based tracking, the engine enables you to build scalable, modular applications with minimal Garbage Collector overhead and zero boilerplate.
Core Patterns
Start designing your data layer with these foundational approaches:
1. Cross-Service Communication & DI
Splitting an application into isolated domain services (AbstractService) and wiring them together via the built-in Dependency Injection container (this.engine.inject). Demonstrates how to compose reactive chains across services without global state or memory leaks.
2. Auto-Batching & High-Frequency Updates
Leveraging built-in update coalescing via the microtask queue (queueMicrotask). Explains how the engine merges multiple synchronous mutations into a single graph pass and when explicit engine.batch() calls are appropriate.
3. Dynamic Dependencies & Link Reuse (LinkPool)
Designing computations with conditional branches (if / else). Explains how the engine automatically unsubscribes inactive branches, recycles detached edges via LinkPool without GC pressure, and preserves O(1) speed using depsCursor.
4. Multi-Instance Isolation & Cross-Engine Bridges
Running multiple independent ReactiveEngine instances within a single application (microfrontends, isolated plugins, SSR) and setting up explicit synchronization bridges between them via .subscribe() or effect.
5. Async Resources & Race Condition Protection (resource)
Declarative network request management via engine.resource(): automatic re-execution on dependency updates, cancellation of stale in-flight requests via AbortController, pre-flight checks (validateBeforeFetch), and payload validation (responseValidate).
6. Optimizing Large Reactive Forms via Proxy (reactive)
Granular property-level reactivity for large nested forms (engine.reactive()) without cloning the entire state tree, paired with synchronous and asynchronous schema validation using withValidationSync and withValidationAsync decorators.
7. Optimistic UI Updates with Automatic Rollback
Instant UI feedback on user actions with state snapshot preservation (previousSnapshot), race-condition cancellation on rapid clicks (AbortController), and automatic rollback on network failures.
8. Request Caching Strategies (withCache & withStaleWhileRevalidate)
TTL-based response caching with parallel Request Collapsing via withCache, and Network-First resilient fallback with LRU memory eviction (maxSize) via withStaleWhileRevalidate.
9. Continuous Server Polling & Exponential Backoff (withLongPolling)
Building a resilient Long Polling pipeline on top of engine.resource() with session token isolation (currentSessionToken), progressive failure backoff, and a dual cancellation circuit (AbortSignal + externalSignal).
10. Rate Limiting Requests & Computations (withDebounce, withThrottle, withThrottleComputed)
Protecting network and CPU layers against high-frequency input streams: delayed fetching (withDebounce), Leading/Trailing network throttling (withThrottle), and capped in-memory recomputations (withThrottleComputed).
11. WebSockets & Real-Time Data Streams
Encapsulating WebSocket connections inside AbstractService with automatic batching of incoming message bursts, reactive reconnection via effect, exponential backoff on disconnects, and strict type-guarded payload parsing.
12. Socket.IO v4+ Integration (Typed Events, Ack & Connection State Recovery)
Building a resilient Socket.IO v4+ client inside AbstractService with typed ServerToClientEvents / ClientToServerEvents contracts, dynamic auth callbacks, promise-based emitWithAck, and socket.recovered state handling.
13. Finite State Machines (FSM) with Signals
Deterministic management of complex multi-step workflows without impossible states, powered by strict TypeScript Discriminated Unions, a send(event) transition dispatcher, and automatic cancellation of exit side effects.
14. Offloading Heavy Computations to Web Workers
Encapsulating background Worker threads inside AbstractService with requestId correlation, engine.resource() integration, cancellation of stale calculations via AbortSignal, and clean thread shutdown via terminate().
15. Персистентность состояния в localStorage и кросс-вкладочная синхронизация
SSR-безопасная гидратация настроек при старте, автосохранение через effect и мгновенная синхронизация между вкладками браузера через событие storage с защитой от циклических перезаписей.
16. Persistence in IndexedDB & Cross-Tab Sync via BroadcastChannel
Non-blocking storage for large offline datasets in IndexedDB paired with engine.resource(), instant cross-tab invalidation via BroadcastChannel, and self-echo protection.
17. Unit Testing Services, Signals & Resources (Vitest / Jest)
Deterministic framework-free unit testing: per-test ReactiveEngine isolation, DI dependency spying, timer fast-forwarding via vi.advanceTimersByTimeAsync(), and AbortSignal cancellation assertions.
18. Connecting Services to UI Frameworks (View Layer Integration)
High-level blueprint for binding AbstractService instances to the view layer without state duplication, with direct links to dedicated React, Vue 3, and Vanilla JS guides.
19. Lazy Service Injection (Lazy Dependency Injection)
Deferring instantiation of auxiliary services via a get service() getter or dynamic import() to speed up cold starts, reduce memory footprint, and break circular dependencies.
General Architectural Principles
Keep these three rules in mind when structuring state in @pravosleva/reactive-engine:
- Keep
computedproperties pure: Usecomputedstrictly for deriving values without side effects or mutating other signals. Move all side effects, logging, and network calls intoeffectorresource. - Isolate business logic in services: Encapsulate signals and state-mutating methods inside
AbstractServiceclasses. This keeps your domain logic completely decoupled from the UI framework (React, Vue, Angular) and simplifies unit testing. - Maintain a predictable read order: Inside dynamic
computedcallbacks, read shared control flags beforeif / elsebranches sodepsCursoralways hits the O(1) fast path.
Expanding Section
This collection is continuously growing with new production patterns: request caching with TTL support (withCache), Optimistic UI updates, and state machine integration.