useSubscription

function useSubscription<T>(
    source,
    options?,
): SubscriptionResult<UnwrapRpcResponse<T>>;

Subscribe to a stream-store source and surface the latest notification as reactive state. The subscription opens on mount, re-opens whenever source changes identity, and tears down on unmount.

Accepts any ReactiveStreamSource — the { reactiveStore() } duck-type satisfied by PendingRpcSubscriptionsRequest (e.g. client.rpcSubscriptions.accountNotifications(addr)) and any plugin-authored stream object that follows the same convention. Pass null to disable; the result reports status: 'disabled'.

Notifications shaped as SolanaRpcResponse<U> (account/program/signature notifications) are unwrapped: data is the inner value U and slot is lifted from context.slot. Raw notifications (slot/logs/root) pass through with slot: undefined.

Memoize the source with useMemo keyed on whatever inputs it depends on; stable identity is how the hook knows when to tear down and re-open.

SSR-safe — on the server the connect effect doesn't run, so the store stays idle and the hook reports status: 'loading'. The first client render hydrates from that same loading paint, then commits the connect effect.

Type Parameters

Type ParameterDescription
TThe raw notification type emitted by the source.

Parameters

ParameterType
sourceReactiveStreamSource<T> | null
options?UseSubscriptionOptions

Returns

SubscriptionResult<UnwrapRpcResponse<T>>

Example

function AccountBalance({ address }: { address: Address }) {
    const client = useClient<ClientWithRpcSubscriptions<AccountNotificationsApi>>();
    const source = useMemo(() => client.rpcSubscriptions.accountNotifications(address), [client, address]);
    const { data, slot, error, reconnect } = useSubscription(source);
    if (error) return <button onClick={reconnect}>Reconnect</button>;
    return <p>{data ? `${data.lamports} lamports at slot ${slot}` : 'Connecting…'}</p>;
}

See

On this page