Build/Frontend

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.

Standard Hooks

For most use cases, the standard hooks (useAPI, useWebsocket, useEventStream) work directly with your routes. These advanced patterns are for custom message handlers and third-party integrations.

useWebsocket

Connect to any WebSocket endpoint:

import { useWebsocket } from '@agentuity/react';
import { useEffect } from 'react';
 
function CustomWebSocket() {
  const { connected, 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: {connected ? 'Connected' : 'Disconnected'}</p>
      <button onClick={handleClick} disabled={!connected}>
        Send Ping
      </button>
      <button onClick={close}>Disconnect</button>
    </div>
  );
}

Return values:

PropertyTypeDescription
connectedbooleanTrue 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 { connected, 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: {connected ? 'Active' : 'Connecting...'}</p>
      <p>Last event: {data?.event ?? 'None'}</p>
      <button onClick={close}>Stop Stream</button>
    </div>
  );
}

Return values:

PropertyTypeDescription
connectedbooleanTrue 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 { connected, 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).

Cleanup

Connections are automatically closed when the component unmounts. You don't need to manually call close() in a cleanup effect.

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

Need Help?

Join our DiscordCommunity for assistance or just to hang with other humans building agents.

Send us an email at hi@agentuity.com if you'd like to get in touch.

Please Follow us on

If you haven't already, please Signup for your free account now and start building your first agent!