npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-nats

v0.1.2

Published

React hooks for NATS messaging and JetStream

Readme

react-nats

React hooks for NATS messaging and JetStream.

Features

  • 🔌 NatsProvider - WebSocket connection management with auto-reconnect
  • 📊 useNatsKvTable - Reactive NATS KV bucket with real-time updates
  • 📨 useNatsStream - JetStream consumer with time-based replay
  • Performance optimized - Batched updates and stable sorting
  • 🎯 TypeScript first - Full type safety with generics
  • 🧪 Zero dependencies - Only peer dependencies on React and NATS

Installation

npm install react-nats @nats-io/nats-core @nats-io/jetstream @nats-io/kv

Quick Start

1. Wrap your app with NatsProvider

import { NatsProvider } from 'react-nats';

function App() {
  return (
    <NatsProvider url="ws://localhost:4222">
      <YourApp />
    </NatsProvider>
  );
}

2. Use NATS KV for real-time data

import { useNatsKvTable } from 'react-nats';

interface MyData {
  id: string;
  value: number;
}

function MyComponent() {
  const entries = useNatsKvTable({
    bucketName: 'my-bucket',
    decoder: {
      decode: (data: Uint8Array) => JSON.parse(new TextDecoder().decode(data)),
    },
    refreshInterval: 50, // Batch updates every 50ms
  });

  return (
    <ul>
      {entries.map((entry) => (
        <li key={entry.key}>
          {entry.key}: {entry.value.value}
        </li>
      ))}
    </ul>
  );
}

3. Consume JetStream messages

import { useNatsStream } from 'react-nats';

function StreamComponent() {
  const messages = useNatsStream({
    stream: 'my-stream',
    subject: 'events.*',
    decoder: {
      decode: (data: Uint8Array) => JSON.parse(new TextDecoder().decode(data)),
    },
    reducer: {
      reduce: (arr, msg) => [...arr, msg].slice(-100), // Keep last 100
    },
    opt_start_time: new Date(Date.now() - 3600000), // Last hour
  });

  return <div>Received {messages.length} messages</div>;
}

API Reference

<NatsProvider>

Manages WebSocket connection to NATS server.

Props:

  • url: string - NATS WebSocket URL (e.g., ws://localhost:4222)
  • options?: Partial<ConnectionOptions> - Additional NATS connection options
  • children: React.ReactNode

Example:

<NatsProvider
  url="wss://nats.example.com"
  options={{
    maxReconnectAttempts: 10,
    reconnectTimeWait: 2000,
  }}
>
  <App />
</NatsProvider>

useNatsConnection()

Returns the current NATS connection or null if not connected.

const connection = useNatsConnection();
if (connection) {
  // Use connection directly
}

useNatsKvTable<T, U>(options)

Watches a NATS KV bucket and returns reactive entries.

Options:

  • bucketName: string - Name of the KV bucket
  • decoder: { decode: (data: Uint8Array) => T } - Decode function for values
  • enrich?: (key: string, created: Date, decoded: T) => U - Optional transform
  • refreshInterval?: number - Batch update interval in ms (default: 50)
  • key?: string | string[] - Filter specific keys

Returns: NatsEntry<U>[]

type NatsEntry<T> = {
  key: string;
  value: T;
  created: Date;
};

Example with enrichment:

const entries = useNatsKvTable({
  bucketName: 'prices',
  decoder: { decode: (data) => parseFloat(new TextDecoder().decode(data)) },
  enrich: (key, created, price) => ({
    symbol: key,
    price,
    age: Date.now() - created.getTime(),
  }),
});

useNatsStream<T>(options)

Consumes messages from a JetStream stream.

Options:

  • stream?: string - Stream name (required)
  • subject?: string | string[] - Filter subjects
  • decoder: { decode: (data: Uint8Array) => T } - Decode function
  • reducer: { reduce: (arr: NatsMessage<T>[], msg: NatsMessage<T>) => NatsMessage<T>[] } - State reducer
  • opt_start_time?: Date - Start consuming from this time

Returns: NatsMessage<T>[]

type NatsMessage<T> = {
  subject: string;
  value: T;
  received: Date;
};

Example with filtering:

const trades = useNatsStream({
  stream: 'TRADES',
  subject: 'trades.BTC.*',
  decoder: { decode: (data) => JSON.parse(new TextDecoder().decode(data)) },
  reducer: {
    reduce: (arr, msg) => {
      // Keep only profitable trades
      if (msg.value.profit > 0) {
        return [...arr, msg];
      }
      return arr;
    },
  },
  opt_start_time: new Date(Date.now() - 86400000), // Last 24 hours
});

Common Patterns

JSON Decoder

const jsonDecoder = {
  decode: (data: Uint8Array) => JSON.parse(new TextDecoder().decode(data)),
};

Protobuf Decoder

import { MyMessage } from './generated/proto';

const protobufDecoder = {
  decode: (data: Uint8Array) => MyMessage.decode(data),
};

Sliding Window Reducer

const slidingWindowReducer = (windowSize: number) => ({
  reduce: (arr: NatsMessage<any>[], msg: NatsMessage<any>) =>
    [...arr, msg].slice(-windowSize),
});

Performance Tips

  1. Batch updates - Use refreshInterval in useNatsKvTable to batch rapid updates
  2. Filter early - Use key parameter to watch only specific keys
  3. Limit state - Use reducer to keep only necessary messages in memory
  4. Memoize decoders - Create decoder objects outside components

Development

# Install dependencies
npm install

# Build the library
npm run build

# Run tests
npm test

# Watch mode
npm run dev

License

MIT

Contributing

Contributions welcome! Please open an issue or PR.