Skip to main content

Internals: Surgical Proxy Usage

SoulState uses JavaScript Proxies for Automatic Dependency Tracking. However, unlike "Full Proxy" libraries where the entire state is wrapped in a permanent proxy, SoulState uses them Surgically to minimize runtime overhead and GC pressure.

Full Proxy vs. Surgical Proxy

Full Proxy Libraries (Valtio, MobX)

In these libraries, your state object is a Proxy. Every property access, even inside tight loops or utility functions, is intercepted by a Proxy get trap.

  • Pros: Perfectly transparent "mutable-style" API.
  • Cons: High runtime overhead, constant trap execution, and high memory footprint.

SoulState's Surgical Proxy

SoulState maintains your state as a Plain Immutable Object. Proxies are only used during the Tracking Phase.

  1. Subscription: When a component calls useStore or a computed is created, SoulState temporarily wraps the current state in a Tracking Proxy.
  2. Execution: The selector runs once against this proxy. The proxy traps every access and records the top-level keys.
  3. Registration: Once the keys are identified, the proxy is discarded. The component/node is then registered in the Invalidation Graph for those specific keys.
  4. Runtime: During subsequent state updates, the component/node is notified directly by the Invalidation Graph. No proxies are involved in the hot-path notification loop.

Reusable Tracking Proxy

SoulState further optimizes this by using a Reusable Tracking Proxy (in src/internals/invalidation.ts).

// Internal Tracking implementation
let currentTarget: any = null;
const sharedAccessedKeys = new Set();

const handler: ProxyHandler<any> = {
get(_, prop) {
trackAccess(prop);
return currentTarget[prop];
}
};

const trackingProxy = new Proxy({}, handler);

By reusing a single Proxy instance and a single Set for key tracking, SoulState minimizes allocations during the tracking phase, which is critical for maintaining high throughput in 100,000+ subscriber scenarios.


Why this matters

By using proxies surgically rather than pervasively:

  1. Native Speed: 99% of your application code interacts with raw, high-performance JavaScript objects.
  2. Minimal GC Pressure: No new Proxy objects are created during the render cycle or state updates.
  3. Debuggability: When you inspect state in the console, you see a plain object, not a complex Proxy structure.

Systems-Grade Efficiency

SoulState delivers the DX of automatic dependency tracking without the performance penalty of permanent proxy wrapping. This surgical approach is what allows SoulState to scale to enterprise-grade reactive graphs.