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

@sodp/react

v0.1.1

Published

React hooks for the State-Oriented Data Protocol

Downloads

210

Readme

@sodp/react

npm license

React bindings for the State-Oriented Data Protocol (SODP) — real-time state sync in your components with a single hook.

Every component that calls useSodpState("my.key") automatically re-renders when the server-side value changes. Multiple components watching the same key share a single WebSocket subscription.

Protocol spec & server · Core client (@sodp/client)


Install

npm install @sodp/react @sodp/client
# or
yarn add @sodp/react @sodp/client

Requires React 18+.


Quick start

Wrap your app in SODPProvider and call useSodpState anywhere inside:

// main.tsx
import { SODPProvider } from "@sodp/react";

root.render(
  <SODPProvider url="wss://sodp.example.com" token={jwt}>
    <App />
  </SODPProvider>
);
// HUD.tsx
import { useSodpState } from "@sodp/react";

interface Player {
  name: string;
  health: number;
  position: { x: number; y: number };
}

function HUD() {
  const [player, meta, ref] = useSodpState<Player>("game.player");

  if (!meta?.initialized) return <div>Loading…</div>;

  return (
    <div>
      <span>{player?.name} — HP: {player?.health}</span>
      <button onClick={() => ref?.patch({ health: (player?.health ?? 0) - 10 })}>
        Take damage
      </button>
    </div>
  );
}

The component re-renders automatically on every delta — no polling, no manual subscriptions.


Provider

<SODPProvider>

Place once near the root of your app. All hooks inside must be descendants of this provider.

<SODPProvider
  url="wss://sodp.example.com"

  // Authentication — pick one:
  token={staticJwt}
  tokenProvider={async () => {
    const res = await fetch("/api/sodp-token");
    return res.text();
  }}

  // Reconnect settings (optional — defaults shown):
  reconnect={true}
  reconnectDelay={1000}
  maxReconnectDelay={30000}

  // Lifecycle callbacks (optional):
  onConnect={() => console.log("connected")}
  onDisconnect={() => console.log("disconnected")}
>
  <App />
</SODPProvider>

The client is created once on mount and closed on unmount. Changing url closes the old client and opens a new one. All other options are read on mount — to rotate a token, remount the provider.


Hooks

useSodpState<T>(key)

Subscribe to a state key and re-render on every update.

Returns a [value, meta, ref] tuple:

| Element | Type | Description | |---|---|---| | value | T \| null | Current state; null if the key has no value yet | | meta | WatchMeta \| null | { version, initialized }, or null before first update | | ref | StateRef<T> \| null | Handle for writes; null while connecting |

function ScoreBoard() {
  const [score, meta, ref] = useSodpState<{ value: number }>("game.score");

  return (
    <div>
      <strong>{score?.value ?? "—"}</strong>
      <button onClick={() => ref?.set({ value: 0 })}>Reset</button>
    </div>
  );
}

Multiple components calling useSodpState with the same key receive the same updates and share one server subscription. When the key changes, the previous key's value is cleared immediately so stale data is never shown.


useSodpRef<T>(key)

Returns a StateRef<T> for write-only access — without subscribing to updates or causing re-renders on change.

Use this in buttons, form handlers, and other places that mutate state but don't need to display it:

function ResetButton() {
  const ref = useSodpRef<{ score: number }>("game.score");

  return (
    <button onClick={() => ref?.set({ score: 0 })}>
      Reset score
    </button>
  );
}

useSodpConnected()

Returns true once the client is connected and authenticated. Use it to show a connection status indicator:

function StatusBar() {
  const connected = useSodpConnected();
  return (
    <span style={{ color: connected ? "green" : "orange" }}>
      {connected ? "Live" : "Reconnecting…"}
    </span>
  );
}

useSodpClient()

Returns the raw SodpClient from the nearest provider. Useful when you need direct access to call(), watch(), or presence():

function CursorTracker() {
  const client = useSodpClient();

  useEffect(() => {
    if (!client) return;
    // Bind cursor to session lifetime — auto-removed on disconnect
    client.presence("collab.cursors", "/alice", { name: "Alice", line: 1 });
  }, [client]);

  return null;
}

Returns null during the brief window between mount and the first WebSocket connection.


Presence (collaborative features)

Presence binds a nested path to the session lifetime. The server automatically removes it and notifies all watchers when the browser tab closes or the network drops — no stale cursors, no ghost "online" badges:

function CollabEditor() {
  const client = useSodpClient();
  const [cursors] = useSodpState<Record<string, { name: string; line: number }>>(
    "collab.cursors"
  );

  useEffect(() => {
    if (!client) return;
    client.presence("collab.cursors", "/alice", { name: "Alice", line: 1 });
  }, [client]);

  return (
    <div>
      {Object.entries(cursors ?? {}).map(([id, c]) => (
        <div key={id}>{c.name} is on line {c.line}</div>
      ))}
    </div>
  );
}

StateRef write API

ref values returned by useSodpState and useSodpRef expose the full write surface:

await ref.set(value)                  // replace full value
await ref.patch({ field: newValue })  // deep-merge partial update
await ref.setIn("/a/b/c", value)      // set nested field by JSON Pointer
await ref.delete()                    // remove key entirely
await ref.presence(path, value)       // session-lifetime path binding
ref.watch(callback)                   // subscribe (returns unsub fn)
ref.get()                             // read cached snapshot
ref.unwatch()                         // cancel subscription + clear local state

TypeScript

All hooks and components are fully typed. Pass your state interface as the type parameter:

interface GameState {
  round: number;
  players: Record<string, { name: string; score: number }>;
}

const [game, meta, ref] = useSodpState<GameState>("game.state");

// ref is StateRef<GameState> — set/patch/setIn are typed
await ref?.patch({ round: 2 });