@natsail/react
v0.7.1
Published
React provider and hooks for NATSail runtimes and shared sessions.
Maintainers
Readme
@natsail/react
@natsail/react provides a NATSail provider, runtime status hooks, session selectors, Core hooks, JetStream hooks, and serial reducer hooks.
pnpm add react @natsail/core @natsail/session @natsail/jetstream @natsail/reactNatsProvider owns neither the runtime nor the session registry. The application closes both objects. NatsManagedProvider is the ownership-safe alternative: it creates both after commit, reuses the resource during React Strict Mode effect replay, and closes it after final unmount. fallback renders until the resource exists, and onCloseError receives a failed close.
Default managed cleanup uses closeNatsResources({ runtime, sessions }) from @natsail/session to start registry and runtime shutdown together so a pending session cannot postpone the runtime's deadline. Identity changes permit temporary overlap: the replacement starts without waiting for the previous resource to drain. A custom resource close() overrides this behavior and remains responsible for both lifetimes; it can delegate to the same helper. See the lifecycle upgrade notes.
<NatsManagedProvider
identity={accountId}
create={() => ({
runtime: createNatsRuntime(runtimeOptions),
sessions: createSessionRegistry({ idleCloseMs: 250 }),
})}
>
<App />
</NatsManagedProvider>useNatsJetStreamSubscription() opens one registry-shared, checkpointed JetStream source. To select from a source, call useNatsSessionSelector(key, createJetStreamSessionSource(runtime, options), selector).
useNatsJetStreamReducer() accepts a validated reducing definition and returns its atomic replay/live snapshot. useNatsJetStreamReducerSelector() can schedule React notifications immediately, in a microtask, or on the next animation frame (the default for both reducer hooks, set with notifications). The underlying session still reduces every delivery serially; only rendering is coalesced.
Both reducer hooks also accept the shared batchPolicy and an optional NatsailScheduler. Count, byte, and time bounds affect React notification delivery only. Replay and recovery phase changes bypass live coalescing.
useNatsConnection() follows the runtime-owned connection for advanced nats.js operations without adding an application connection effect.
useNatsJetStreamProcessor() owns one explicit-ack processor lease. Pass null options to disable it without conditionally calling a hook; change the key when its consumer configuration changes. A replacement waits for the previous lease to close, so an owned consumer cannot be recreated while its prior lease is still deleting it. When processor recovery is enabled, the hook reports reconnecting and the restart count without requiring a React remount.
See the NATSail README for React examples.
License
Apache-2.0
