---
name: use_websocket
kind: component
lang: ts
domain: core
version: "1.0.0"
purity: impure
signature: "useWebSocket<TSend, TRecv>(opts: UseWebSocketOptions<TSend, TRecv>): UseWebSocketResult<TSend, TRecv>"
description: "Hook WebSocket con auto-reconexion y backoff exponencial. Serializa envios como JSON, parsea recepcion como JSON. Buffer de mensajes con limite configurable. Mensajes en vuelo se bufferean hasta reconectar."
tags: [websocket, ws, hook, realtime, reconnect, stream, core, component]
uses_functions: []
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: [react]
params:
  - name: url
    desc: "URL del WebSocket (ej: ws://localhost:8484/ws/chat)"
  - name: enabled
    desc: "Si conecta automaticamente al montar (default true)"
  - name: reconnect
    desc: "Si reconecta automaticamente con backoff exponencial (default true)"
  - name: reconnect_interval
    desc: "Delay inicial de reconexion en ms (default 1000)"
  - name: max_reconnect_interval
    desc: "Delay maximo de reconexion en ms (default 30000)"
  - name: max_messages
    desc: "Numero maximo de mensajes a mantener en buffer (default 100)"
  - name: on_message
    desc: "Callback por cada mensaje recibido con el dato parseado"
output: "Objeto con send, last_message, messages[], status (connecting/open/closing/closed), close() y connect()"
tested: false
tests: []
test_file_path: ""
file_path: "frontend/functions/core/use_websocket.tsx"
props:
  - name: url
    type: "string"
    required: true
    description: "URL del WebSocket"
  - name: enabled
    type: "boolean"
    required: false
    description: "Conectar al montar (default true)"
  - name: reconnect
    type: "boolean"
    required: false
    description: "Auto-reconectar (default true)"
  - name: reconnect_interval
    type: "number"
    required: false
    description: "Delay inicial reconexion en ms (default 1000)"
  - name: max_reconnect_interval
    type: "number"
    required: false
    description: "Delay maximo reconexion en ms (default 30000)"
  - name: max_messages
    type: "number"
    required: false
    description: "Tamano del buffer de mensajes (default 100)"
emits: [on_message, on_open, on_close, on_error]
has_state: true
framework: react
variant: [default]
---

## Ejemplo

```tsx
import { useWebSocket } from '@/functions/core/use_websocket'

interface ChatMessage { user: string; text: string; ts: number }
interface SendMessage { text: string }

function Chat() {
  const { send, messages, status } = useWebSocket<SendMessage, ChatMessage>({
    url: 'ws://localhost:8484/ws/chat',
    reconnect: true,
    max_messages: 50,
  })

  const [input, setInput] = useState('')

  return (
    <div>
      <div>Status: {status}</div>
      <div style={{ height: 300, overflow: 'auto' }}>
        {messages.map((msg, i) => (
          <div key={i}><b>{msg.user}:</b> {msg.text}</div>
        ))}
      </div>
      <input
        value={input}
        disabled={status !== 'open'}
        onChange={(e) => setInput(e.currentTarget.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' && input.trim()) {
            send({ text: input })
            setInput('')
          }
        }}
      />
    </div>
  )
}
```

## Notas

- Genericos separados: `TSend` para envio, `TRecv` para recepcion (pueden diferir)
- Mensajes enviados antes de `open` se bufferean y envian al conectar
- El buffer `messages` se limita a `max_messages` (FIFO, elimina el mas viejo)
- El backoff exponencial duplica el delay hasta `max_reconnect_interval`
- `close()` previene reconexion automatica; `connect()` fuerza reconexion manual
