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-socket-store

v0.0.5

Published

It is for easily using Websocket in React.It inspired by React-redux.

Readme

react-socket-store

npm version

It is for easily using Websocket in React. It inspired by React-redux. It is provider of socket-store.

react-socket-store depends on the public socket-store package contract. Its source imports runtime values and store contract types from the socket-store package root, not from generated socket-store/dist/* build paths.

Full guides are published at nerdchanii.github.io/react-socket-store. For version pairing and upgrade guidance, see Compatibility and Migration.

Package Boundary and Compatibility

socket-store owns framework-agnostic WebSocket behavior: message handler routing, topic state updates, send({ key, data }), getState(key), subscription semantics, unknown-key behavior, duplicate handler validation, and connection lifecycle callbacks.

react-socket-store owns the React integration layer: SocketProvider, store-direct hooks, useSocketStoreRef, schema-safe hook types, and React subscription cleanup through useSyncExternalStore.

The current adapter release depends on socket-store@^0.0.3. React-facing APIs remain compatible with the previous adapter release, so this is a patch upgrade for consumers already using the public package root exports.

Quick Start

1. Install

#npm

npm install react-socket-store socket-store

#yarn

yarn add react-socket-store socket-store

2. Create MessageHandler(s), and Socket Store

MesssageHandler and Socket store is based on socket-store.

2-1. Create MessageHandler

First, create a message handler. Define the topic, callback for the topic, and default status. This will be provided in the store.

  • createMessageHandler(key, callback, state)
    • key : it will be subject of message.
    • callback: it will works like reducer. it must return state!
    • state: it is defualt state.
import { createMessageHandler } from "react-socket-store";

const talkHandler = createMessageHandler<string[], string>(
  "talk",
  (state, data) => {
    return [...state, data];
  },
  []
);

2-2. Create SocketStore

Next, create a socket store. Store gets two or three parameters for web sockets and message handlers.

  1. WebSocket instance,
  2. array of message handler,
  3. options options has callbacks about connection status.
  • new SocketStore(ws: WebSocket, messageHandlers: MessageHandler[], options?: SocketStoreOptions)
import { SocketStore } from "react-socket-store";

const socketStore = new SocketStore(new WebSocket("ws://localhost:3000"), [
  talkHandler,
]);

2-3. Store Ownership

You can pass a store directly to hooks when a component owns its realtime boundary. Store-direct hooks are the preferred shape for focused client islands, data-loader patterns, and Next.js App Router code because they avoid widening a larger React tree into a client boundary. Keep WebSocket allocation out of render-phase hook initializers; pass a stable client-owned store into the component instead.

import {
  useSocket,
  useSocketStoreRef,
  type ISocketStore,
} from "react-socket-store";

function ChatClient({ store }: { store: ISocketStore<ChatSchema> }) {
  const stableStore = useSocketStoreRef(() => store);
  const [messages, sendTalk] = useSocket(stableStore, "talk");

  sendTalk("hello");

  return <p>{messages.join(", ")}</p>;
}

SocketProvider remains available as an optional SPA-friendly convenience when many descendants share the same store through context. Do not put SocketProvider at the app root when only one focused subtree needs realtime state, or when doing so would force a server-rendered layout, route, or data-loader boundary to become client-rendered. In those cases, pass the store directly to useSocket, useListen, or useSend.

  • Wrap the SPA subtree that needs socket state with <SocketProvider>, and provide a previously created store as a prop for the socket provider.
import type { ReactNode } from "react";
import { SocketProvider, type ISocketStore } from "react-socket-store";

type ChatSchema = {
  talk: {
    state: string[];
    payload: string;
  };
};

function AppRoot({
  store,
  children,
}: {
  store: ISocketStore<ChatSchema>;
  children: ReactNode;
}) {
  return (
    <SocketProvider<ChatSchema> store={store}>
      {children}
    </SocketProvider>
  );
}

3. Use SocketStore with Hook

we supply API for using SocketStore, by hooks.

3-1. useSocket

useSocket gets the parameter for the key of the MessageHandler, and returns the state, and sendfunction for the key.

import { FormEvent, useState } from "react";
import { useSocket } from "react-socket-store";

function ChatBox() {
  const [value, setValue] = useState("");
  const [messages, sendTalk] = useSocket<ChatSchema, "talk">("talk");

  function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    sendTalk(value);
    setValue("");
  }

  return (
    <>
      <div>
        {messages.map((message) => (
          <span key={message}>{message}</span>
        ))}
      </div>
      <form onSubmit={submit}>
        <input value={value} onChange={(event) => setValue(event.target.value)} />
      </form>
    </>
  );
}

For topic-safe state and send payloads, provide a schema type:

type ChatSchema = {
  talk: {
    state: string[];
    payload: string;
  };
  trade: {
    state: string | null;
    payload: string;
  };
};

const [messages, sendTalk] = useSocket<ChatSchema, "talk">("talk");

sendTalk("hello");
// TypeScript error: "talk" payloads must be strings.
sendTalk(123);

3-2. useSend

useSend gets the paramerter for the key of the MessageHandler, and returns only sendfunction for the key.

import { FormEvent, useState } from "react";
import { useSend } from "react-socket-store";

function SendBox() {
  const [value, setValue] = useState("");
  const [sendTalk] = useSend<ChatSchema, "talk">("talk");

  function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    sendTalk(value);
  }

  return (
    <form onSubmit={submit}>
      <input value={value} onChange={(event) => setValue(event.target.value)} />
    </form>
  );
}

3-3. useListen

useListen gets the paramerter for the key of the MessageHandler, and returns only state for the key.

import { useListen } from "react-socket-store";

function MessageList() {
  const [messages] = useListen<ChatSchema, "talk">("talk");

  return (
    <div>
      {messages.map((message) => (
        <span key={message}>{message}</span>
      ))}
    </div>
  );
}

The README examples are mirrored by test-d/readme.test-d.tsx.

Contributors 👏🏻

LICENSE