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 — React hooks including useChat for streaming chat with full type safety in React apps."
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, providing convenient React bindings for the headless client.
16
17For a typed headless chat UI, see [React Chat UI](../ui/react).
18For React Native, the documented support surface is narrow: `useChat` with chat
19connection adapters. React DOM-specific UI packages and TanStack AI devtools UI
20are not part of the React Native support surface.
21
22For a complete native journey, see
23[Quick Start: React Native](../getting-started/quick-start-react-native).
24
25## Installation
26
27<!-- ::start:tabs variant="package-manager" mode="install" -->
28
29react: @tanstack/ai-react
30
31<!-- ::end:tabs -->
32
33## `useRegisterWebMCPTools(tools, options?)`
34
35Register executable client tools after the React component mounts. React removes them on cleanup and replaces them when `tools` or `options` change.
36
37For a complete setup and behavior guide, see [WebMCP Tools](../tools/webmcp).
38
39```tsx
40import {
41 useRegisterWebMCPTools,
42 type UseRegisterWebMCPToolsOptions,
43} from "@tanstack/ai-react";
44import { searchProducts } from "./tools";
45
46const tools = [searchProducts];
47const options: UseRegisterWebMCPToolsOptions<typeof tools> = {
48 onError(error) {
49 console.error(error);
50 },
51};
52
53function ProductsPage() {
54 useRegisterWebMCPTools(tools, options);
55 return null;
56}
57```
58
59`UseRegisterWebMCPToolsOptions<TTools, TContext>` contains `toolOptions`, `context`, and `onError`. The hook owns the registration signal.
60
61The `context` field is required when a tool declares a required runtime context. Keep `tools` and `options` stable when their values do not change.
62
63## `usePageWebMCPTools(options?)`
64
65Read the WebMCP tools on the page as client tools. The array starts empty and updates when the page adds or removes a tool. Pass it to `useChat` as `tools`.
66
67```tsx
68import { usePageWebMCPTools } from "@tanstack/ai-react";
69
70export function useSameOriginPageTools() {
71 return usePageWebMCPTools({
72 filter: (tool) => tool.origin === location.origin,
73 });
74}
75```
76
77`filter` skips a tool when it returns `false`. `onError` gets a failed WebMCP read. For a complete guide, see [Page WebMCP Tools in Chat](../tools/webmcp-page-tools).
78
79## `createChatHook(options)`
80
81Bind `chatOptions` once at module scope. Call `useChat()` in the screen to create the instance. Per-call overrides may set `threadId`, `initialMessages`, `live`, and `forwardedProps`. They must not change `tools`, `interrupts`, or `outputSchema`.
82
83```tsx
84import { createChatHook, fetchServerSentEvents } from "@tanstack/ai-react";
85
86const chatOptions = {
87 connection: fetchServerSentEvents("/api/chat"),
88};
89
90const { useChat } = createChatHook(chatOptions);
91
92function ChatScreen() {
93 const chat = useChat({ threadId: "support-1" });
94 return null;
95}
96```
97
98`useChat(chatOptions)` from this package still works when you want to pass the full object at the call site. Rename the bound hook if both are in one file: `const { useChat: useSupportChat } = createChatHook(chatOptions)`.
99
100## `useChat(options?)`
101
102Main hook for managing chat state in React with full type safety.
103
104```tsx
105import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
106import {
107 createChatClientOptions,
108 type InferChatMessages
109} from "@tanstack/ai-client";
110import { toolDefinition } from "@tanstack/ai";
111import { z } from "zod";
112import { useState } from "react";
113
114const updateUIDef = toolDefinition({
115 name: "updateUI",
116 description: "Update the UI with a notification",
117 inputSchema: z.object({
118 message: z.string(),
119 }),
120 outputSchema: z.object({ success: z.boolean() }),
121});
122
123function ChatComponent() {
124 const [notification, setNotification] = useState<string | null>(null);
125
126 // Create client tool implementations
127 const updateUI = updateUIDef.client((input) => {
128 setNotification(input.message);
129 return { success: true };
130 });
131
132 // Create typed tools array (no 'as const' needed!)
133 const tools = [updateUI];
134
135 const chatOptions = createChatClientOptions({
136 connection: fetchServerSentEvents("/api/chat"),
137 tools,
138 });
139
140 // Fully typed messages!
141 type ChatMessages = InferChatMessages<typeof chatOptions>;
142
143 const { messages, sendMessage, isLoading, error, addToolApprovalResponse } =
144 useChat(chatOptions);
145
146 return <div>{/* Chat UI with typed messages */}</div>;
147}
148```
149
150### Options
151
152Extends `ChatClientOptions` from `@tanstack/ai-client`:
153
154- `connection` - Connection adapter (required)
155- `tools?` - Array of client tool implementations (with `.client()` method)
156- `initialMessages?` - Initial messages array
157- `threadId?` - The only identity for this chat. Required when persistence is on. If omitted, minted after mount.
158- `forwardedProps?` - Arbitrary client-controlled JSON forwarded to the server in the AG-UI `RunAgentInput.forwardedProps` field (e.g., `{ provider: 'openai', model: 'gpt-5.5' }`)
159- `body?` - **Deprecated.** Use `forwardedProps` instead. Still works for backward compatibility; values are merged into `forwardedProps` on the wire
160- `byok?` - Optional BYOK keyring from `defineByok`. On each send the client prepares the resolved provider and stamps `x-byok-*` request headers. Keys never go in the body
161- `byokProvider?` - Optional function that returns the provider slug for this chat. If it returns a slug, only that key is prepared and sent. Otherwise the merged `provider` from `forwardedProps`, `body`, and per-call `sendMessage` `body` is used. Later sources win. If no slug resolves, the send throws instead of attaching every stored key
162- `context?` - Typed client-local runtime context passed to client tool implementations. This value is not serialized to the server
163- `onResponse?` - Callback when response is received
164- `onChunk?` - Callback when stream chunk is received
165- `onFinish?` - Callback when response finishes
166- `onError?` - Callback when error occurs
167- `onInterruptStateChange?` - Callback when interrupt state changes; context source is `hydrate` for restored state and `live` for streamed or client-initiated updates
168- `streamProcessor?` - Stream processing configuration
169
170**Note:** Client tools are now automatically executed - no `onToolCall` callback needed!
171
172### Returns
173
174```typescript
175import type { UIMessage } from "@tanstack/ai-react";
176import type { ModelMessage } from "@tanstack/ai";
177import type {
178 MultimodalContent,
179 SendMessageOptions,
180} from "@tanstack/ai-client";
181
182interface UseChatReturn {
183 messages: UIMessage[];
184 sendMessage: (
185 content: string | MultimodalContent,
186 options?: SendMessageOptions,
187 ) => Promise<void>;
188 append: (message: ModelMessage | UIMessage) => Promise<void>;
189 addToolResult: (result: {
190 toolCallId: string;
191 tool: string;
192 output: any;
193 state?: "output-available" | "output-error";
194 errorText?: string;
195 }) => Promise<void>;
196 addToolApprovalResponse: (response: {
197 id: string;
198 approved: boolean;
199 }) => Promise<void>;
200 reload: () => Promise<void>;
201 stop: () => void;
202 isLoading: boolean;
203 error: Error | undefined;
204 setMessages: (messages: UIMessage[]) => void;
205 clear: () => void;
206}
207```
208
209## `useByok(client)`
210
211Subscribe to a `ByokClient` snapshot in React.
212
213```tsx
214import { useByok } from "@tanstack/ai-react";
215import { byok } from "./byok";
216
217export function KeyStatus() {
218 const snapshot = useByok(byok);
219 const openai = snapshot.status.openai;
220 const last4 = openai && "masked" in openai ? openai.masked : "No key";
221 return <p>{last4}</p>;
222}
223```
224
225`snapshot` has `status`, `locked`, and `prompt`. Call `byok.update(provider, value)` from your own UI to save a key. See [Bring Your Own Key](../advanced/byok).
226
227## Connection Adapters
228
229Re-exported from `@tanstack/ai-client` for convenience:
230
231```typescript
232import {
233 fetchServerSentEvents,
234 fetchHttpStream,
235 xhrServerSentEvents,
236 xhrHttpStream,
237 stream,
238 type ConnectionAdapter,
239 type FetchConnectionOptions,
240 type XhrConnectionOptions,
241} from "@tanstack/ai-react";
242```
243
244For React Native or Expo chat screens, use an absolute server URL and prefer
245`xhrHttpStream()` with a server route that returns `toHttpResponse()`. Use
246`xhrServerSentEvents()` with `toServerSentEventsResponse()` when you want SSE.
247Use `fetchHttpStream()` only when the runtime supports streaming `fetch`,
248`Response.body.getReader()`, and `TextDecoder`; otherwise it throws
249`UnsupportedResponseStreamError`.
250
251XHR adapter options include `headers`, `withCredentials`, `signal`, `body`, and
252`xhrFactory`. Fetch adapter options include `headers`, `credentials`, `signal`,
253`body`, and `fetchClient`. Both option objects may be provided directly or as a
254function that resolves per request.
255
256For error narrowing, import `UnsupportedResponseStreamError` and
257`StreamTruncatedError` from `@tanstack/ai-client`.
258
259## Example: Basic Chat
260
261```tsx
262import { useState } from "react";
263import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
264
265export function Chat() {
266 const [input, setInput] = useState("");
267
268 const { messages, sendMessage, isLoading } = useChat({
269 connection: fetchServerSentEvents("/api/chat"),
270 });
271
272 const handleSubmit = (e: React.FormEvent) => {
273 e.preventDefault();
274 if (input.trim() && !isLoading) {
275 sendMessage(input);
276 setInput("");
277 }
278 };
279
280 return (
281 <div>
282 <div>
283 {messages.map((message) => (
284 <div key={message.id}>
285 <strong>{message.role}:</strong>
286 {message.parts.map((part, idx) => {
287 if (part.type === "thinking") {
288 return (
289 <div key={idx} className="text-sm text-gray-500 italic">
290 💭 Thinking: {part.content}
291 </div>
292 );
293 }
294 if (part.type === "text") {
295 return <span key={idx}>{part.content}</span>;
296 }
297 return null;
298 })}
299 </div>
300 ))}
301 </div>
302 <form onSubmit={handleSubmit}>
303 <input
304 value={input}
305 onChange={(e) => setInput(e.target.value)}
306 disabled={isLoading}
307 />
308 <button type="submit" disabled={isLoading}>
309 Send
310 </button>
311 </form>
312 </div>
313 );
314}
315```
316
317## Example: Tool Approval
318
319```tsx
320import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
321
322export function ChatWithApproval() {
323 const { messages, sendMessage, addToolApprovalResponse } = useChat({
324 connection: fetchServerSentEvents("/api/chat"),
325 });
326
327 return (
328 <div>
329 {messages.map((message) =>
330 message.parts.map((part) => {
331 if (
332 part.type === "tool-call" &&
333 part.state === "approval-requested" &&
334 part.approval
335 ) {
336 return (
337 <div key={part.id}>
338 <p>Approve: {part.name}</p>
339 <button
340 onClick={() =>
341 addToolApprovalResponse({
342 id: part.approval!.id,
343 approved: true,
344 })
345 }
346 >
347 Approve
348 </button>
349 <button
350 onClick={() =>
351 addToolApprovalResponse({
352 id: part.approval!.id,
353 approved: false,
354 })
355 }
356 >
357 Deny
358 </button>
359 </div>
360 );
361 }
362 return null;
363 })
364 )}
365 </div>
366 );
367}
368```
369
370## Example: Client Tools with Type Safety
371
372```tsx
373import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
374import {
375 createChatClientOptions,
376 type InferChatMessages
377} from "@tanstack/ai-client";
378import { toolDefinition } from "@tanstack/ai";
379import { z } from "zod";
380import { useState } from "react";
381
382const updateUIDef = toolDefinition({
383 name: "updateUI",
384 description: "Update the UI with a notification",
385 inputSchema: z.object({
386 message: z.string(),
387 type: z.string(),
388 }),
389 outputSchema: z.object({ success: z.boolean() }),
390});
391
392const saveToStorageDef = toolDefinition({
393 name: "saveToStorage",
394 description: "Save a value to storage",
395 inputSchema: z.object({
396 key: z.string(),
397 value: z.string(),
398 }),
399 outputSchema: z.object({ saved: z.boolean() }),
400});
401
402export function ChatWithClientTools() {
403 const [notification, setNotification] = useState<{ message: string; type: string } | null>(null);
404
405 // Create client implementations
406 const updateUI = updateUIDef.client((input) => {
407 // ✅ input is fully typed!
408 setNotification({ message: input.message, type: input.type });
409 return { success: true };
410 });
411
412 const saveToStorage = saveToStorageDef.client((input) => {
413 localStorage.setItem(input.key, input.value);
414 return { saved: true };
415 });
416
417 // Create typed tools array (no 'as const' needed!)
418 const tools = [updateUI, saveToStorage];
419
420 const { messages, sendMessage } = useChat({
421 connection: fetchServerSentEvents("/api/chat"),
422 tools, // ✅ Automatic execution, full type safety
423 });
424
425 return (
426 <div>
427 {messages.map((message) =>
428 message.parts.map((part) => {
429 if (part.type === "tool-call" && part.name === "updateUI") {
430 // ✅ part.input and part.output are fully typed!
431 return <div key={part.id}>Tool executed: {part.name}</div>;
432 }
433 return null;
434 })
435 )}
436 </div>
437 );
438}
439```
440
441## `createChatClientOptions(options)`
442
443Helper to create typed chat options (re-exported from `@tanstack/ai-client`).
444
445```typescript
446import {
447 createChatClientOptions,
448 fetchServerSentEvents,
449 type InferChatMessages
450} from "@tanstack/ai-client";
451import { tool1, tool2 } from "./tools";
452
453// Create typed tools array (no 'as const' needed!)
454const tools = [tool1, tool2];
455
456const chatOptions = createChatClientOptions({
457 connection: fetchServerSentEvents("/api/chat"),
458 tools,
459});
460
461type Messages = InferChatMessages<typeof chatOptions>;
462```
463
464## Types
465
466Re-exported from `@tanstack/ai-client`:
467
468- `UIMessage<TTools>` - Message type with tool type parameter
469- `MessagePart<TTools>` - Message part with tool type parameter
470- `TextPart` - Text content part
471- `ThinkingPart` - Thinking content part
472- `ToolCallPart<TTools>` - Tool call part (discriminated union)
473- `ToolResultPart` - Tool result part
474- `ChatClientOptions<TTools, TContext>` - Chat client options with typed client runtime context
475- `ConnectionAdapter` - Connection adapter interface
476- `InferChatMessages<T>` - Extract message type from options
477
478Re-exported from `@tanstack/ai`:
479
480- `toolDefinition()` - Create isomorphic tool definition
481- `ToolDefinitionInstance` - Tool definition type
482- `ClientTool` - Client tool type
483- `ServerTool` - Server tool type
484
485## Next Steps
486
487- [Getting Started](../getting-started/quick-start) - Learn the basics
488- [Bring Your Own Key](../advanced/byok) - Store keys and pass `byok` into `useChat`
489- [Tools Guide](../tools/tools) - Learn about the isomorphic tool system
490- [Client Tools](../tools/client-tools) - Learn about client-side tools