useSocket
A WebSocket client hook with auto-reconnect. It wraps the browser's native WebSocket API — no
socket.io-client, no ws, no dependency at all. This works because contextIsolation/sandbox
only block Node.js APIs in the renderer, not Web APIs; WebSocket is available exactly like in any
browser tab. There is no IPC channel involved — the renderer connects directly to the target
ws:///wss:// server, bypassing the main process entirely.
const { status, lastMessage, send, connect, disconnect } = useSocket(url, options)
| Param/Member | Type | Notes |
|---|---|---|
url | string | null | Pass null to skip connecting (e.g. while an auth token loads). |
options.protocols | string | string[] | Forwarded to the WebSocket constructor. |
options.reconnect | boolean (default true) | Auto-reconnect after an unexpected close. |
options.reconnectInterval | number (default 2000) | Delay in ms between reconnect attempts. |
options.maxReconnectAttempts | number (default Infinity) | Caps reconnect attempts. |
options.onOpen/onClose/onError/onMessage | callbacks | Raw DOM event/MessageEvent access. |
status | 'idle' | 'connecting' | 'open' | 'closed' | 'error' | Current connection state. |
lastMessage | MessageEvent | null | Most recent message received. |
send | (data: string | Blob | BufferSource) => boolean | Sends if open; returns false (no-op) otherwise. |
connect | () => void | Manually (re)connect. |
disconnect | (code?, reason?) => void | Closes and disables auto-reconnect for this instance. |
'use client'import { useSocket } from 'nextop-app'export default function LiveTicker() {const { status, lastMessage, send } = useSocket('wss://example.com/feed')return (<div><p>Status: {status}</p><button onClick={() => send(JSON.stringify({ type: 'ping' }))}>Ping</button>{lastMessage && <p>Last: {lastMessage.data}</p>}</div>)}
This connects to an external WebSocket server (your own backend, a realtime API, etc.). It is not a way to push events from the Electron main process to the renderer — use
ipcRenderer(via the other hooks) for that; there's no socket round-trip needed for same-process communication.