useRealtime
Pick WebSocket or SSE transport.
Import
TypeScript
import { useRealtime } from '@/hooks';API
Signature
useRealtime(url, { transport?, ... })
When to use
Use useRealtime instead of re-implementing the same pattern in multiple components.
SSR / Next.js
Connect only in the browser / Client Components.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useRealtimeEditor
function Chat() { const rt = useRealtime(process.env.NEXT_PUBLIC_WS_URL, { transport: 'websocket', }); return ( <div> <p>{rt.status}</p> <button onClick={() => rt.send?.('hi')}>Send</button> </div> ); }
Preview
Implementation source
Full library source for useRealtime — copy into your project when you are not installing a package yet.
hooks/network/useRealtime.ts
import { useWebSocket, type UseWebSocketOptions } from './useWebSocket';
import { useEventSource, type UseEventSourceOptions } from './useEventSource';
export type RealtimeTransport = 'websocket' | 'sse';
export interface UseRealtimeOptions {
transport?: RealtimeTransport;
websocket?: UseWebSocketOptions;
sse?: UseEventSourceOptions;
}
/**
* Unified realtime connector. Chooses WebSocket or SSE transport.
* Always pass the endpoint URL from the call site.
*/
export function useRealtime(
url: string | null | undefined,
options: UseRealtimeOptions = {},
) {
const { transport = 'websocket', websocket, sse } = options;
// Both hooks must be called unconditionally — gate with null URL.
const ws = useWebSocket(transport === 'websocket' ? url : null, {
autoConnect: transport === 'websocket',
...websocket,
});
const es = useEventSource(transport === 'sse' ? url : null, {
autoConnect: transport === 'sse',
...sse,
});
if (transport === 'sse') {
return {
transport,
status: es.status,
lastEvent: es.lastEvent,
connect: es.connect,
disconnect: es.disconnect,
retryCount: es.retryCount,
send: undefined as undefined,
} as const;
}
return {
transport,
status: ws.status,
lastEvent: ws.lastMessage,
connect: ws.connect,
disconnect: ws.disconnect,
retryCount: ws.retryCount,
send: ws.send,
} as const;
}
Copy-paste example
useRealtime.example.tsx
'use client';
import { useRealtime } from '@/hooks';
export function Chat() {
const rt = useRealtime(process.env.NEXT_PUBLIC_WS_URL, {
transport: 'websocket',
});
return (
<div>
<p>{rt.status}</p>
<button onClick={() => rt.send?.('hi')}>Send</button>
</div>
);
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Never hardcode URLs in components shared across envs — use env vars.
- Source of truth: open
hooks/network/useRealtime.tsfor implementation details