Advanced Hooks — Agentuity Documentation

Advanced Hooks

Connect to custom WebSocket and SSE endpoints with useWebsocket and useEventStream

For custom endpoints that aren't agents, use the low-level hooks directly.

useWebsocket

Connect to any WebSocket endpoint:

import { useWebsocket } from '@agentuity/react';
import { useEffect } from 'react';
 
function CustomWebSocket() {
  const { isConnected, send, data, setHandler, close } = useWebsocket<
    { action: string },  // Input type
    { result: string }   // Output type
  >('/custom/websocket');
 
  // Set a custom message handler
  useEffect(() => {
    setHandler((message) => {
      console.log('Received:', message);
      // Process message as needed
    });
  }, [setHandler]);
 
  const handleClick = () => {
    send({ action: 'ping' });
  };
 
  return (
    <div>
      <p>Status: {isConnected ? 'Connected' : 'Disconnected'}</p>
      <button onClick={handleClick} disabled={!isConnected}>
        Send Ping
      </button>
      <button onClick={close}>Disconnect</button>
    </div>
  );
}

Return values:

PropertyTypeDescription
isConnectedbooleanTrue when WebSocket is open
send(data: TInput) => voidSend a message
dataTOutput | undefinedLast received message
setHandler(fn: (data: TOutput) => void) => voidCustom message handler
readyStatenumberWebSocket ready state
close() => voidClose the connection
reset() => voidClear error state
errorError | nullConnection error

useEventStream

Connect to any Server-Sent Events endpoint:

import { useEventStream } from '@agentuity/react';
import { useEffect } from 'react';
 
function CustomEventStream() {
  const { isConnected, data, setHandler, close, error } = useEventStream<
    { event: string; timestamp: number }
  >('/custom/events');
 
  useEffect(() => {
    setHandler((event) => {
      console.log('Event received:', event);
    });
  }, [setHandler]);
 
  if (error) {
    return <p>Error: {error.message}</p>;
  }
 
  return (
    <div>
      <p>Stream: {isConnected ? 'Active' : 'Connecting...'}</p>
      <p>Last event: {data?.event ?? 'None'}</p>
      <button onClick={close}>Stop Stream</button>
    </div>
  );
}

Return values:

PropertyTypeDescription
isConnectedbooleanTrue when stream is active
dataTOutput | undefinedLast received event
setHandler(fn: (data: TOutput) => void) => voidCustom event handler
readyStatenumberConnection state
close() => voidClose the stream
reset() => voidClear error state
errorError | nullConnection error

Options

Both hooks accept options for customizing the connection:

const { isConnected, send } = useWebsocket('/path', {
  query: new URLSearchParams({ token: 'abc123' }),
  subpath: '/room/1',  // Appends to path
  signal: abortController.signal,
});

Reconnection Behavior

Both hooks automatically reconnect when the connection drops using exponential backoff (delays increase between attempts, capped at 30 seconds).

When to Use These

Use CaseRecommended Hook
HTTP API routesuseAPI
WebSocket routesuseWebsocket
SSE routesuseEventStream
Third-party WebSocketuseWebsocket with custom handler
Custom SSE endpointuseEventStream with custom handler

Next Steps