A tracked, ref-counted reference to a resolved service.

Provides memory-safe access: accessing .current after .release() throws RefReleasedError instead of returning a stale value.

1.2.0

const rpcRef = ctx.acquireRef(Tokens.RPC);

// Use the service
const balance = await rpcRef.current.getBalance(pubkey);

// Release when done (e.g. on unmount)
rpcRef.release();

// Accessing after release throws
rpcRef.current; // ❌ RefReleasedError

Type Parameters

  • T

    The service type.

Implements

Constructors

  • Internal

    Use ctx.acquireRef(token) or RefRegistry.acquire() to create refs.

    Type Parameters

    • T

    Parameters

    • _value: T
    • _token: ServiceToken<T>
    • _onRelease: ((ref: ServiceRef<T>) => void)
    • id: number

      Unique reference ID (monotonically increasing within a registry).

    Returns ServiceRef<T>

Properties

id: number

Unique reference ID (monotonically increasing within a registry).

Accessors

  • get acquiredAt(): number
  • performance.now() timestamp when this ref was acquired.

    Returns number

  • get alive(): boolean
  • Whether this reference is still valid (not released).

    Returns boolean

  • get current(): T
  • The resolved service instance.

    Returns T

    If the ref has been released or invalidated.

Methods

  • Release this reference, decrementing the ref count.

    After release:

    • .current throws RefReleasedError
    • .alive returns false
    • The ref count for this token decreases by 1

    Safe to call multiple times (idempotent).

    Returns void

  • Create a weak reference that does not prevent garbage collection.

    The returned WeakServiceRef can be shared to components that only need the service optionally — if the strong refs are all released and the GC collects the object, .deref() returns undefined instead of throwing.

    Returns WeakServiceRef<T & object>

    If the service value is a primitive (not weakly referenceable).

    const weakRpc = rpcRef.toWeak();
    // Later:
    const rpc = weakRpc.deref();
    if (rpc) rpc.getBalance(pubkey);
  • Execute a function with this reference, auto-releasing afterward.

    The ref is released in a finally block, guaranteeing cleanup even if the function throws.

    Type Parameters

    • R

    Parameters

    • fn: ((service: T) => R)

      Receives the unwrapped service value.

        • (service): R
        • Parameters

          • service: T

          Returns R

    Returns R

    The return value of fn.

    const balance = rpcRef.use(rpc => rpc.getBalance(pubkey));
    // rpcRef is now released — no leak possible
  • Async version of use. Awaits the function, then releases.

    Type Parameters

    • R

    Parameters

    • fn: ((service: T) => Promise<R>)
        • (service): Promise<R>
        • Parameters

          • service: T

          Returns Promise<R>

    Returns Promise<R>

    const balance = await rpcRef.useAsync(rpc => rpc.getBalance(pubkey));