Skip to content

Type-safe React hooks & provider for Socket.IO with auto-reconnect, auth token refresh, room helpers, optimistic updates, and RPC (ack) requests. React 18+.

License

Notifications You must be signed in to change notification settings

empellio/react-socket

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@empellio/react-socket

Type-safe React hooks & provider for Socket.IO with auto-reconnect, auth token refresh, room helpers, optimistic updates, and RPC (ack) requests. React 18+.

Installation

npm install @empellio/react-socket socket.io-client

Quick start (typed)

// types.ts
import { createSocketTypes } from '@empellio/react-socket'

type ServerToClient = {
  'room:message': { roomId: string; message: string; userId: string; ts: number }
}
type ClientToServer = {
  'room:send': { roomId: string; message: string }
}

export const api = createSocketTypes<ServerToClient, ClientToServer>()
// App.tsx
import { api } from './types'
const { SocketProvider } = api

export function App() {
  return (
    <SocketProvider url={import.meta.env.VITE_SOCKET_URL} namespace="/chat">
      <YourApp />
    </SocketProvider>
  )
}

More docs coming soon.

API Reference

  • SocketProvider(props)
    • url, namespace, autoConnect, getToken, auth, transports, reconnection, reconnectionAttempts, reconnectionDelay, reconnectionDelayMax, timeout, query, onConnectError, onAuthError
  • SocketBoundary({ children, fallback })
  • useSocket() → { socket, connected, connecting, error, latencyMs, attempts, lastError, reconnectIn }
  • useSocketEvent(event, handler, deps?)
  • useEmit(event) → { emit, emitAck, loading, error }
  • useRequest(event, { timeout? }) → { call, loading, error }
  • useRoom(roomId, { autoJoin?, deps? }) → { join, leave, inRoom }
  • usePresence() → { users, lastUpdate }
  • useOptimistic(selector) → (event, optimisticUpdate, rollback?) → { emit }
  • useConnection() → { connected, connecting, attempts, lastError, reconnectIn }
  • useLatency(intervalMs?) → { latencyMs }
  • useSubchannel(event, key, handler, deps?)
  • SocketDevtools overlay (enable with localStorage.setItem('empellio:debug','react-socket:*'))

Auth & Token refresh

  • On connect, if getToken is provided, its result is added to auth.token.
  • On connect_error with 401/invalid token, the provider retries by calling getToken() again and reconnects. onAuthError is called if refresh fails.

Reconnect/backoff metadata

  • useConnection() exposes attempts, lastError, and reconnectIn (estimated ms until next try based on backoff config).

Offline queue & auto rejoin

  • Emits while offline are queued up to 30s and replayed on reconnect.
  • Joined rooms are remembered and rejoined automatically after reconnect.

Rooms & Presence

  • useRoom(roomId) emits room:join/room:leave with ack callbacks and tracks membership.
  • usePresence() listens to presence:update conventionally and keeps users and lastUpdate.

RPC / Ack

  • useEmit(event).emitAck(payload, { timeout, signal }) returns the ack result or throws on timeout/abort.
  • useRequest(event) is a convenience wrapper with loading/error state.

Optimistic UI

const [list, setList] = useState<string[]>([])
const optimistic = useOptimistic(() => [list, setList])
const { emit } = optimistic('room:send', ({ message }) => [...list, message])

SSR notes

  • Provider defers socket creation until effects run (no window access on server). Hooks are no-ops on server.

About

Type-safe React hooks & provider for Socket.IO with auto-reconnect, auth token refresh, room helpers, optimistic updates, and RPC (ack) requests. React 18+.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published