React Hooks API Reference
The @inngest/use-agent package provides a comprehensive set of React hooks for building AI chat interfaces with AgentKit networks. This reference section documents every hook, component, and utility in detail.
Package Overview
Section titled “Package Overview”npm install @inngest/use-agent# Peer dependenciesnpm install react @inngest/realtime uuidCore Hooks
Section titled “Core Hooks”These hooks provide the primary functionality for building AI chat applications:
Infrastructure Components
Section titled “Infrastructure Components”Essential components for connection management and configuration:
Utility Hooks
Section titled “Utility Hooks”Specialized hooks for specific features and UI patterns:
Package Architecture
Section titled “Package Architecture”Hook Categories
Section titled “Hook Categories”Core Streaming Hooks:
useAgent: Multi-thread real-time streaminguseChat: Complete chat application functionalityuseThreads: Thread persistence and management
Specialized Storage:
useEphemeralThreads: Client-side storage for demosuseConversationBranching: Message editing workflows
UI Utilities:
useMessageActions: Copy, like, share, read alouduseEditMessage: Message editing state managementuseSidebar: Responsive sidebar stateuseIsMobile: Mobile device detection
Infrastructure:
AgentProvider: Shared context and connections- Transport layer: Configurable API communication
Design Principles
Section titled “Design Principles”🎯 Progressive Enhancement:
Start simple with useChat, add advanced hooks as needed
🔧 Composable Architecture: Hooks work independently or together based on your needs
⚡ Performance First: Intelligent connection sharing and efficient state management
🛡️ Production Ready: Comprehensive error handling, TypeScript support, and testing
🔄 Backward Compatible: Smooth migration from local implementations to package
Type System
Section titled “Type System”Core Types
Section titled “Core Types”All hooks use consistent, well-defined TypeScript interfaces:
import type { // Message and content types ConversationMessage, MessagePart, TextUIPart, ToolCallUIPart, HitlUIPart,
// State and status types AgentStatus, Thread, ThreadState,
// Event and streaming types NetworkEvent, AgentMessageChunk,
// Transport and configuration AgentTransport, UseAgentOptions, UseChatConfig,
// Error handling AgentError, ErrorClassification,} from "@inngest/use-agent";Hook Return Types
Section titled “Hook Return Types”Each hook has a comprehensive return type interface:
import type { UseAgentReturn, UseChatReturn, UseThreadsReturn,} from "@inngest/use-agent";
// Example: Complete typing for useChatconst chat: UseChatReturn = useChat({ initialThreadId: "thread-123",});Common Patterns
Section titled “Common Patterns”Basic Chat Application
Section titled “Basic Chat Application”import { useChat, AgentProvider } from "@inngest/use-agent";
function App() { return ( <AgentProvider userId="user-123"> <ChatInterface /> </AgentProvider> );}
function ChatInterface() { const { messages, // ConversationMessage[] sendMessage, // (message: string) => Promise<void> status, // AgentStatus isConnected, // boolean threads, // Thread[] switchToThread, // (threadId: string) => Promise<void> createNewThread // () => string } = useChat();
return <div>/* Your chat UI */</div>;}Custom Transport Configuration
Section titled “Custom Transport Configuration”import { AgentProvider, createDefaultAgentTransport, type DefaultAgentTransportConfig} from "@inngest/use-agent";
const transport: DefaultAgentTransportConfig = { api: { sendMessage: '/api/v2/chat', fetchThreads: '/api/v2/conversations' }, headers: { 'Authorization': `Bearer ${token}` }};
<AgentProvider transport={transport}> <ChatApp /></AgentProvider>Multi-thread Management
Section titled “Multi-thread Management”import { useAgent } from "@inngest/use-agent";
function AdvancedChat() { const { threads, // Record<string, ThreadState> currentThreadId, // string setCurrentThread, // (threadId: string) => void sendMessageToThread, // (threadId: string, message: string) => Promise<void> getThread, // (threadId: string) => ThreadState | undefined createThread, // (threadId: string) => void removeThread // (threadId: string) => void } = useAgent({ threadId: 'initial-thread', userId: 'user-123' });
return <div>/* Custom multi-thread UI */</div>;}Performance Guidelines
Section titled “Performance Guidelines”Memory Management
Section titled “Memory Management”✅ Efficient Patterns:
// Stable configuration objectsconst transportConfig = useMemo( () => ({ headers: { Authorization: `Bearer ${token}` }, }), [token]);
// Reasonable state capturestate: () => ({ currentTab: activeTab, formData: getCurrentForm(),});❌ Memory Leaks:
// Don't capture massive objectsstate: () => ({ entireAppState: store.getState(), // Too large! allUserHistory: history, // Too large!});
// Don't recreate config on every rendertransport: createDefaultAgentTransport({ // New instance! headers: { Authorization: `Bearer ${token}` },});Connection Optimization
Section titled “Connection Optimization”✅ Efficient:
// Single provider, shared connections<AgentProvider userId="user-123"> <ChatSidebar /> {/* Shares connection */} <ChatMain /> {/* Shares connection */}</AgentProvider>❌ Inefficient:
// Multiple separate connections<ChatSidebar /> {/* useThreads creates connection */}<ChatMain /> {/* useAgent creates connection */}Error Handling
Section titled “Error Handling”Rich Error Objects
Section titled “Rich Error Objects”All hooks provide comprehensive error information:
const { error, connectionError, clearError } = useChat();
if (error) { console.log({ message: error.message, // Human-readable error recoverable: error.recoverable, // Can user retry? timestamp: error.timestamp, // When it occurred suggestion: error.suggestion, // How to fix });}Error Recovery Patterns
Section titled “Error Recovery Patterns”// Automatic retry for recoverable errorsuseEffect(() => { if (error?.recoverable) { const timer = setTimeout(() => { clearError(); // Optionally retry the failed operation }, 3000); return () => clearTimeout(timer); }}, [error]);Debug Utilities
Section titled “Debug Utilities”Debug Logging
Section titled “Debug Logging”Enable comprehensive debug output:
import { createDebugLogger } from "@inngest/use-agent";
const logger = createDebugLogger("MyComponent", true);logger.log("Component initialized");logger.warn("Non-critical issue");logger.error("Critical error");Development vs Production
Section titled “Development vs Production”<AgentProvider debug={process.env.NODE_ENV === 'development'} transport={isDev ? devTransport : prodTransport}> <ChatApp /></AgentProvider>Migration Guide
Section titled “Migration Guide”From Local Implementations
Section titled “From Local Implementations”// Before: Local imports from examplesimport { useChat } from "@/hooks/use-chat";import { AgentProvider } from "@/contexts/AgentContext";
// After: Package importsimport { useChat, AgentProvider } from "@inngest/use-agent";No API changes required - the package maintains full backward compatibility with local implementations.
Version Compatibility
Section titled “Version Compatibility”| Package Version | AgentKit Version | React Version | Features |
|---|---|---|---|
| 1.0.0+ | 0.3.0+ | 18.0.0+ | Full feature set |
| 0.9.0+ | 0.2.0+ | 18.0.0+ | Beta features |
Next Steps
Section titled “Next Steps”This reference section provides the definitive documentation for every aspect of the @inngest/use-agent package. Whether you’re just getting started or building advanced custom implementations, you’ll find the complete API documentation and guidance you need here.