Open History to see the last commit
1---
2title: "@tanstack/ai-react"
3slug: /api/ai-react
4order: 3
5description: "API reference for @tanstack/ai-react: the useChat hook, generation hooks, and React bindings for the headless TanStack AI client."
6keywords:
7 - tanstack ai
8 - "@tanstack/ai-react"
9 - react
10 - useChat
11 - react hooks
12 - api reference
13---
14
15React hooks for TanStack AI. To build your first chat, start with the [Quick Start](../getting-started/quick-start). For a typed chat layout, see [React Chat UI](../ui/react).
16
17## Installation
18
19<!-- ::start:tabs variant="package-manager" mode="install" -->
20
21react: @tanstack/ai-react
22
23<!-- ::end:tabs -->
24
25The package works in React Native and Expo, but only `useChat` with chat connection adapters is supported there. See [Quick Start: React Native](../getting-started/quick-start-react-native).
26
27## `useChat(options)`
28
29Holds the messages and the run state of one chat, and talks to your server route.
30
31```tsx
32import { useState } from "react";
33import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
34
35export function Chat() {
36 const [input, setInput] = useState("");
37 const { messages, sendMessage, isLoading } = useChat({
38 connection: fetchServerSentEvents("/api/chat"),
39 threadId: "support-chat",
40 });
41
42 return (
43 <div>
44 {messages.map((message) => (
45 <div key={message.id}>
46 <strong>{message.role}:</strong>
47 {message.parts.map((part, idx) =>
48 part.type === "text" ? <span key={idx}>{part.content}</span> : null,
49 )}
50 </div>
51 ))}
52 <form
53 onSubmit={(e) => {
54 e.preventDefault();
55 if (input.trim() && !isLoading) {
56 sendMessage(input);
57 setInput("");
58 }
59 }}
60 >
61 <input value={input} onChange={(e) => setInput(e.target.value)} />
62 <button type="submit" disabled={isLoading}>
63 Send
64 </button>
65 </form>
66 </div>
67 );
68}
69```
70
71### Options
72
73You must pass `threadId`. You must also pass `connection` or `fetcher`, not both.
74
75| Option | What it does |
76| --- | --- |
77| `connection` | Connection adapter, for example `fetchServerSentEvents("/api/chat")`. See [Transports](../transports/overview). |
78| `fetcher` | A function that returns a `Response` or a stream. Use it with server functions. |
79| `tools` | Client tools from `.client()`. They run when the model calls them. See [Client Tools](../tools/client-tools). |
80| `threadId` | Required. The id of this chat. Use a stable id for each conversation, for example the id from your route. |
81| `initialMessages` | The messages to show first. |
82| `forwardedProps` | JSON sent to the server in the AG-UI `forwardedProps` field, for example `{ model: "gpt-6.1-sol" }`. |
83| `persistence` | `true` to load the thread from the server, or a storage adapter. See [Chat Persistence](../persistence/chat-persistence). |
84| `outputSchema` | A Standard Schema. Adds typed `partial` and `final` to the return value. See [Streaming structured output](../structured-outputs/streaming). |
85| `context` | Client-only runtime context for client tools. It is not sent to the server. |
86| `live` | Subscribe on mount and unsubscribe on unmount. |
87| `queue` | What `sendMessage` does while a run is busy. Default: queue the message. See [Queueing](../chat/queueing). |
88| `interrupts` | Definitions from `defineInterrupt()`. See [Interrupts](../interrupts/overview). |
89| `subagents` | Agents from `defineAgent()`, for types only. See [Subagents](../chat/subagents). |
90| `byok`, `byokProvider` | A keyring from `defineByok()`. See [Bring Your Own Key](../advanced/byok). |
91| `devtools` | Display options for TanStack AI Devtools. |
92
93The hook also takes the `ChatClient` callbacks (`onResponse`, `onChunk`, `onFinish`, `onError`, `onInterruptStateChange`, `onCustomEvent`) and the other client options. See [`ChatClient` options](./ai-client#constructor-options).
94
95When `forwardedProps`, `tools`, `context`, or `queue` change, the hook updates the current chat.
96
97### Returns
98
99State values are plain React values. The hook renders again when they change.
100
101| Field | What it is |
102| --- | --- |
103| `messages` | The `UIMessage` array of the chat. |
104| `sendMessage(content, options?)` | Sends a user message. `content` is a string or `{ content, id?, metadata? }`. `options` takes `whenBusy` and `body`. |
105| `isLoading` | `true` while a response streams. |
106| `error` | The last error, or `undefined`. |
107| `status` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. |
108| `stop()` | Stops the current response. |
109| `reload()` | Sends the last user message again. |
110| `append(message)` | Adds a `UIMessage` or `ModelMessage` and starts a run. |
111| `addToolResult(result)` | Gives the result of a client tool by hand: `{ toolCallId, tool, output, state?, errorText? }`. |
112| `setMessages(messages)`, `clear()` | Replace or clear the messages. |
113| `queue`, `cancelQueued(id)` | Messages that wait while a run is busy. See [Queueing](../chat/queueing). |
114| `runId` | The id of the run in flight, or `null`. |
115| `interrupts` | Pending interrupts. Each item has `resolveInterrupt(...)`. See [Interrupts](../interrupts/overview). |
116| `resolveInterrupts`, `cancelInterrupts`, `retryInterrupts`, `resumeInterruptsUnsafe` | Act on all pending interrupts at once. |
117| `interruptErrors`, `resuming` | Errors from the last resume, and `true` while a resume runs. |
118| `isHydrating` | `true` while the chat loads from persistence. |
119| `hasOlderMessages`, `loadOlderMessages()` | Page in older messages. See [Chat Persistence](../persistence/chat-persistence). |
120| `isSubscribed`, `connectionStatus`, `sessionGenerating` | State of the live subscription. |
121| `partial`, `final` | Structured output. Only when you pass `outputSchema`. |
122| `subagents` | Live child-agent runs. See [Subagents](../chat/subagents). |
123
124### Example: tool approval
125
126A tool with `needsApproval: true` pauses the run. The pending call shows up in `interrupts`.
127
128```tsx
129import { toolDefinition } from "@tanstack/ai";
130import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
131import { z } from "zod";
132
133const deleteFileTool = toolDefinition({
134 name: "delete_file",
135 description: "Delete a file",
136 needsApproval: true,
137 inputSchema: z.object({ path: z.string() }),
138});
139
140export function ChatWithApproval() {
141 const { interrupts } = useChat({
142 connection: fetchServerSentEvents("/api/chat"),
143 threadId: "support-chat",
144 tools: [deleteFileTool],
145 });
146
147 return (
148 <div>
149 {interrupts.map((interrupt) =>
150 interrupt.kind === "tool-approval" ? (
151 <div key={interrupt.id}>
152 <p>Approve: {interrupt.toolName}</p>
153 <button onClick={() => interrupt.resolveInterrupt(true)}>
154 Approve
155 </button>
156 <button onClick={() => interrupt.resolveInterrupt(false)}>
157 Deny
158 </button>
159 </div>
160 ) : null,
161 )}
162 </div>
163 );
164}
165```
166
167See [Tool Approval](../interrupts/tool-approval) for the server side.
168
169## `createChatHook(options)`
170
171Binds chat options once at module scope and returns a `useChat` hook that uses them.
172
173```tsx
174import { createChatHook, fetchServerSentEvents } from "@tanstack/ai-react";
175
176const { useChat: useSupportChat } = createChatHook({
177 connection: fetchServerSentEvents("/api/chat"),
178});
179
180export function SupportScreen() {
181 const chat = useSupportChat({ threadId: "support-1" });
182 return <p>{chat.messages.length} messages</p>;
183}
184```
185
186The bound hook takes these per-call overrides: `threadId`, `initialMessages`, `live`, and `forwardedProps`. Keep `tools`, `interrupts`, and `outputSchema` on the factory options.
187
188`@tanstack/ai-react/ui` has its own `createChatHook` that also returns typed UI components. See [React Chat UI](../ui/react).
189
190## Generation hooks
191
192Each hook runs one generation request and keeps its result. See [Generation Hooks](../media/generation-hooks).
193
194| Hook | `generate()` input | `result` |
195| --- | --- | --- |
196| `useGenerateImage` | `ImageGenerateInput` | `ImageGenerationResult` |
197| `useGenerateAudio` | `AudioGenerateInput` | `AudioGenerationResult` |
198| `useGenerateSpeech` | `SpeechGenerateInput` | `TTSResult` |
199| `useTranscription` | `TranscriptionGenerateInput` | `TranscriptionResult` |
200| `useSummarize` | `SummarizeGenerateInput` | `SummarizationResult` |
201| `useGenerateVideo` | `VideoGenerateInput` | `VideoGenerateResult` |
202| `useGeneration` | Your own input type | Your own result type |
203
204```tsx
205import { useGenerateImage, fetchServerSentEvents } from "@tanstack/ai-react";
206
207export function ImageButton() {
208 const image = useGenerateImage({
209 connection: fetchServerSentEvents("/api/generate/image"),
210 threadId: "image-studio",
211 });
212
213 return (
214 <button
215 disabled={image.isLoading}
216 onClick={() => image.generate({ prompt: "A mountain at sunset" })}
217 >
218 Generate
219 </button>
220 );
221}
222```
223
224Options: `threadId` (required), `connection` or `fetcher`, `body`, `persistence`, `byok`, `byokProvider`, `devtools`, `onResult`, `onError`, `onProgress`, `onChunk`.
225
226Returns: `generate(input)`, `result`, `isLoading`, `error`, `status`, `stop()`, `reset()`, `runId`.
227
228`useGenerateVideo` also returns `jobId` and `videoStatus`, and takes `onJobCreated` and `onStatusUpdate`.
229
230## `useRealtimeChat(options)`
231
232Runs a voice conversation with a realtime model. Pass `getToken` and `adapter`. See [Realtime Chat](../media/realtime-chat).
233
234```tsx
235import { useRealtimeChat } from "@tanstack/ai-react";
236import { openaiRealtime } from "@tanstack/ai-openai";
237
238export function VoiceChat() {
239 const chat = useRealtimeChat({
240 getToken: () => fetch("/api/realtime-token").then((r) => r.json()),
241 adapter: openaiRealtime(),
242 });
243
244 return chat.status === "idle" ? (
245 <button onClick={() => chat.connect()}>Start</button>
246 ) : (
247 <button onClick={() => chat.disconnect()}>Stop</button>
248 );
249}
250```
251
252Returns `status`, `error`, `mode`, `messages`, `connect()`, `disconnect()`, `startListening()`, `stopListening()`, `interrupt()`, `sendText(text)`, `sendImage(data, mimeType)`, `updateSession(config)`, plus audio levels and frequency data for visualizers.
253
254## `useAudioRecorder(options?)`
255
256Records audio from the microphone. See [Audio Recording](../media/audio-recording).
257
258Returns `recording`, `isRecording`, `isSupported`, `start()`, `stop()`, and `cancel()`. Pass `onComplete` to transform the recording. Then `recording` and `stop()` use the transformed type.
259
260## `useByok(client)`
261
262Subscribes to a BYOK keyring and returns its snapshot. See [Bring Your Own Key](../advanced/byok).
263
264```tsx
265import { useByok } from "@tanstack/ai-react";
266import { byok } from "./byok";
267
268export function KeyStatus() {
269 const snapshot = useByok(byok);
270 const openai = snapshot.status.openai;
271 return <p>{openai && "masked" in openai ? openai.masked : "No key"}</p>;
272}
273```
274
275The snapshot has `status`, `locked`, `prompt`, and `storageError`. Save a key from your own UI with `byok.update(provider, value)`.
276
277## `useMcpAppBridge(options)`
278
279Returns a stable MCP App bridge for one thread. It always calls the latest `chat.sendMessage` and `onLink`. Options: `threadId`, `callEndpoint`, `chat`, `fetchImpl`, `onLink`. See [MCP Apps](../mcp/apps).
280
281The `MCPAppResource` component, which renders a `ui-resource` part, is on the `@tanstack/ai-react/mcp-apps` subpath.
282
283## `useRegisterWebMCPTools(tools, options?)`
284
285Exposes client tools to the browser WebMCP API while the component is mounted. See [WebMCP Tools](../tools/webmcp).
286
287```tsx
288import { useRegisterWebMCPTools } from "@tanstack/ai-react";
289import { searchProducts } from "./tools";
290
291const tools = [searchProducts];
292
293export function ProductsPage() {
294 useRegisterWebMCPTools(tools, {
295 onError: (error) => console.error(error),
296 });
297 return null;
298}
299```
300
301Options: `toolOptions`, `context`, and `onError`. `context` is required when a tool declares a required runtime context. The hook registers the tools again when `tools` or `options` change, so keep them stable.
302
303## `usePageWebMCPTools(options?)`
304
305Reads the WebMCP tools that the page registered, as client tools. The array starts empty and updates when the page adds or removes a tool. Pass it to `useChat` as `tools`. See [Page WebMCP Tools in Chat](../tools/webmcp-page-tools).
306
307```tsx
308import { usePageWebMCPTools } from "@tanstack/ai-react";
309
310export function useSameOriginPageTools() {
311 return usePageWebMCPTools({
312 filter: (tool) => tool.origin === location.origin,
313 });
314}
315```
316
317Options: `filter` (return `false` to skip a tool) and `onError`.
318
319## Re-exports from `@tanstack/ai-client`
320
321You can import these from `@tanstack/ai-react` directly. See [`@tanstack/ai-client`](./ai-client) for details.
322
323| Group | Exports |
324| --- | --- |
325| Connection adapters | `fetchServerSentEvents`, `fetchHttpStream`, `fetchJson`, `xhrServerSentEvents`, `xhrHttpStream`, `webSocket`, `stream`, `rpcStream` |
326| Typed options | `createChatClientOptions`, `clientTools` |
327| Persistence | `localStoragePersistence`, `sessionStoragePersistence`, `indexedDBPersistence` |
328| Clients | `ChatClient`, `GenerationClient`, `VideoGenerationClient`, `RealtimeClient`, `AudioRecorder`, `InterruptManager` |
329| WebMCP and MCP Apps | `registerWebMCPTools`, `getWebMCPTools`, `subscribeWebMCPTools`, `createMcpAppBridge` |
330| Errors | `UnsupportedResponseStreamError`, `StreamTruncatedError`, `DurableStreamIncompleteError`, `StreamReconnectLimitError`, `StorageUnavailableError` |
331| Stream helpers | `StreamProcessor`, chunk strategies, `parsePartialJSON`, message converters |
332
333For React Native or Expo, use an absolute server URL and `xhrHttpStream()` with a route that returns `toHttpResponse()`. If the host cannot stream, use `fetchJson()` with `toJsonResponse()`. See [React Native](../transports/react-native).
334
335BYOK helpers (`defineByok`, `defaultByokStorage`, and more) are on the `@tanstack/ai-react/byok` subpath.
336
337## Types
338
339| Type | What it is |
340| --- | --- |
341| `UseChatOptions`, `UseChatReturn` | The options and return value of `useChat`. |
342| `UIMessage<TTools>` | A chat message with typed parts. |
343| `InferChatMessages<T>` | The message type for a `createChatClientOptions` result. |
344| `SendMessageOptions`, `WhenBusy`, `QueueOption`, `QueuedMessage` | Send and queue types. |
345| `DeepPartial<T>` | The type of `partial` while structured output streams. |
346| `Use<Hook>Options`, `Use<Hook>Return` | Options and return types for the generation, realtime, and recorder hooks. The WebMCP hooks export only an options type. |
347
348Pass a plain tools array to `useChat` or `createChatClientOptions`. Tool names, inputs, and outputs stay typed without `as const`. Import `toolDefinition` from `@tanstack/ai`.