@void-snippets/react

createSocketHooks

Type-safe Socket.IO hook factory bound to a socket instance.

#What it does

Generates three typed hooks bound to a specific Socket.IO socket instance. Your event type definitions are passed once to the factory, so every hook call site is fully typed without generics.

#Setup — two files, done once

1. Declare your event types globally:

typescript
// src/socket-protocols.d.ts
declare global {
  interface IClientToServerEvents {
    'join-room':      (roomId: string) => void;
    'send-message':   (msg: { text: string; roomId: string }) => void;
    'update-profile': (name: string, callback: (res: { status: 'ok' | 'error' }) => void) => void;
  }

  interface IServerToClientEvents {
    'new-message':  (data: { text: string; from: string; roomId: string }) => void;
    'user-joined':  (userId: string) => void;
    error:          (code: number, msg: string) => void;
  }
}

2. Create the socket and the hooks:

typescript
// services/socket-hooks.ts
import { createSocketHooks } from '@void-snippets/react';
import { io } from 'socket.io-client';

const socket = io(import.meta.env.VITE_SOCKET_URL, {
  autoConnect:          false, // connect explicitly — do not auto-connect on import
  reconnectionAttempts: 5,
  reconnectionDelay:    2000,
});

export const { useSocketEmit, useSocketListener, useSocketConnection } =
  createSocketHooks<IClientToServerEvents, IServerToClientEvents>(socket);

Import the three hooks from services/socket-hooks.ts throughout your app.