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.
16For React Native, the documented support surface is narrow: `useChat` with chat
17connection adapters. React DOM-specific UI packages and TanStack AI devtools UI
18are not part of the React Native support surface.
19
20For a complete native journey, see
21[Quick Start: React Native](../getting-started/quick-start-react-native).
22
23## Installation
24
25```bash
26npm install @tanstack/ai-react
27```
28
29## `useChat(options?)`
30
31Main hook for managing chat state in React with full type safety.
32
33```tsx
34import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
35import {
36 createChatClientOptions,
37 type InferChatMessages
38} from "@tanstack/ai-client";
39import { toolDefinition } from "@tanstack/ai";
40import { z } from "zod";
41import { useState } from "react";
42
43const updateUIDef = toolDefinition({
44 name: "updateUI",
45 description: "Update the UI with a notification",
46 inputSchema: z.object({
47 message: z.string(),
48 }),
49 outputSchema: z.object({ success: z.boolean() }),
50});
51
52function ChatComponent() {
53 const [notification, setNotification] = useState<string | null>(null);
54
55 // Create client tool implementations
56 const updateUI = updateUIDef.client((input) => {
57 setNotification(input.message);
58 return { success: true };
59 });
60
61 // Create typed tools array (no 'as const' needed!)
62 const tools = [updateUI];
63
64 const chatOptions = createChatClientOptions({
65 connection: fetchServerSentEvents("/api/chat"),
66 tools,
67 });
68
69 // Fully typed messages!
70 type ChatMessages = InferChatMessages<typeof chatOptions>;
71
72 const { messages, sendMessage, isLoading, error, addToolApprovalResponse } =
73 useChat(chatOptions);
74
75 return <div>{/* Chat UI with typed messages */}</div>;
76}
77```
78
79### Options
80
81Extends `ChatClientOptions` from `@tanstack/ai-client`:
82
83- `connection` - Connection adapter (required)
84- `tools?` - Array of client tool implementations (with `.client()` method)
85- `initialMessages?` - Initial messages array
86- `id?` - Unique identifier for this chat instance
87- `threadId?` - Thread ID for AG-UI run correlation. Persists across sends; auto-generated if omitted
88- `forwardedProps?` - Arbitrary client-controlled JSON forwarded to the server in the AG-UI `RunAgentInput.forwardedProps` field (e.g., `{ provider: 'openai', model: 'gpt-4o' }`)
89- `body?` - **Deprecated.** Use `forwardedProps` instead. Still works for backward compatibility; values are merged into `forwardedProps` on the wire
90- `context?` - Typed client-local runtime context passed to client tool implementations. This value is not serialized to the server
91- `onResponse?` - Callback when response is received
92- `onChunk?` - Callback when stream chunk is received
93- `onFinish?` - Callback when response finishes
94- `onError?` - Callback when error occurs
95- `streamProcessor?` - Stream processing configuration
96
97**Note:** Client tools are now automatically executed - no `onToolCall` callback needed!
98
99### Returns
100
101```typescript
102import type { UIMessage } from "@tanstack/ai-react";
103import type { ModelMessage } from "@tanstack/ai";
104
105interface UseChatReturn {
106 messages: UIMessage[];
107 sendMessage: (content: string) => Promise<void>;
108 append: (message: ModelMessage | UIMessage) => Promise<void>;
109 addToolResult: (result: {
110 toolCallId: string;
111 tool: string;
112 output: any;
113 state?: "output-available" | "output-error";
114 errorText?: string;
115 }) => Promise<void>;
116 addToolApprovalResponse: (response: {
117 id: string;
118 approved: boolean;
119 }) => Promise<void>;
120 reload: () => Promise<void>;
121 stop: () => void;
122 isLoading: boolean;
123 error: Error | undefined;
124 setMessages: (messages: UIMessage[]) => void;
125 clear: () => void;
126}
127```
128
129## Connection Adapters
130
131Re-exported from `@tanstack/ai-client` for convenience:
132
133```typescript
134import {
135 fetchServerSentEvents,
136 fetchHttpStream,
137 xhrServerSentEvents,
138 xhrHttpStream,
139 stream,
140 type ConnectionAdapter,
141 type FetchConnectionOptions,
142 type XhrConnectionOptions,
143} from "@tanstack/ai-react";
144```
145
146For React Native or Expo chat screens, use an absolute server URL and prefer
147`xhrHttpStream()` with a server route that returns `toHttpResponse()`. Use
148`xhrServerSentEvents()` with `toServerSentEventsResponse()` when you want SSE.
149Use `fetchHttpStream()` only when the runtime supports streaming `fetch`,
150`Response.body.getReader()`, and `TextDecoder`; otherwise it throws
151`UnsupportedResponseStreamError`.
152
153XHR adapter options include `headers`, `withCredentials`, `signal`, `body`, and
154`xhrFactory`. Fetch adapter options include `headers`, `credentials`, `signal`,
155`body`, and `fetchClient`. Both option objects may be provided directly or as a
156function that resolves per request.
157
158For error narrowing, import `UnsupportedResponseStreamError` and
159`StreamTruncatedError` from `@tanstack/ai-client`.
160
161## Example: Basic Chat
162
163```tsx
164import { useState } from "react";
165import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
166
167export function Chat() {
168 const [input, setInput] = useState("");
169
170 const { messages, sendMessage, isLoading } = useChat({
171 connection: fetchServerSentEvents("/api/chat"),
172 });
173
174 const handleSubmit = (e: React.FormEvent) => {
175 e.preventDefault();
176 if (input.trim() && !isLoading) {
177 sendMessage(input);
178 setInput("");
179 }
180 };
181
182 return (
183 <div>
184 <div>
185 {messages.map((message) => (
186 <div key={message.id}>
187 <strong>{message.role}:</strong>
188 {message.parts.map((part, idx) => {
189 if (part.type === "thinking") {
190 return (
191 <div key={idx} className="text-sm text-gray-500 italic">
192 💭 Thinking: {part.content}
193 </div>
194 );
195 }
196 if (part.type === "text") {
197 return <span key={idx}>{part.content}</span>;
198 }
199 return null;
200 })}
201 </div>
202 ))}
203 </div>
204 <form onSubmit={handleSubmit}>
205 <input
206 value={input}
207 onChange={(e) => setInput(e.target.value)}
208 disabled={isLoading}
209 />
210 <button type="submit" disabled={isLoading}>
211 Send
212 </button>
213 </form>
214 </div>
215 );
216}
217```
218
219## Example: Tool Approval
220
221```tsx
222import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
223
224export function ChatWithApproval() {
225 const { messages, sendMessage, addToolApprovalResponse } = useChat({
226 connection: fetchServerSentEvents("/api/chat"),
227 });
228
229 return (
230 <div>
231 {messages.map((message) =>
232 message.parts.map((part) => {
233 if (
234 part.type === "tool-call" &&
235 part.state === "approval-requested" &&
236 part.approval
237 ) {
238 return (
239 <div key={part.id}>
240 <p>Approve: {part.name}</p>
241 <button
242 onClick={() =>
243 addToolApprovalResponse({
244 id: part.approval!.id,
245 approved: true,
246 })
247 }
248 >
249 Approve
250 </button>
251 <button
252 onClick={() =>
253 addToolApprovalResponse({
254 id: part.approval!.id,
255 approved: false,
256 })
257 }
258 >
259 Deny
260 </button>
261 </div>
262 );
263 }
264 return null;
265 })
266 )}
267 </div>
268 );
269}
270```
271
272## Example: Client Tools with Type Safety
273
274```tsx
275import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
276import {
277 createChatClientOptions,
278 type InferChatMessages
279} from "@tanstack/ai-client";
280import { toolDefinition } from "@tanstack/ai";
281import { z } from "zod";
282import { useState } from "react";
283
284const updateUIDef = toolDefinition({
285 name: "updateUI",
286 description: "Update the UI with a notification",
287 inputSchema: z.object({
288 message: z.string(),
289 type: z.string(),
290 }),
291 outputSchema: z.object({ success: z.boolean() }),
292});
293
294const saveToStorageDef = toolDefinition({
295 name: "saveToStorage",
296 description: "Save a value to storage",
297 inputSchema: z.object({
298 key: z.string(),
299 value: z.string(),
300 }),
301 outputSchema: z.object({ saved: z.boolean() }),
302});
303
304export function ChatWithClientTools() {
305 const [notification, setNotification] = useState<{ message: string; type: string } | null>(null);
306
307 // Create client implementations
308 const updateUI = updateUIDef.client((input) => {
309 // ✅ input is fully typed!
310 setNotification({ message: input.message, type: input.type });
311 return { success: true };
312 });
313
314 const saveToStorage = saveToStorageDef.client((input) => {
315 localStorage.setItem(input.key, input.value);
316 return { saved: true };
317 });
318
319 // Create typed tools array (no 'as const' needed!)
320 const tools = [updateUI, saveToStorage];
321
322 const { messages, sendMessage } = useChat({
323 connection: fetchServerSentEvents("/api/chat"),
324 tools, // ✅ Automatic execution, full type safety
325 });
326
327 return (
328 <div>
329 {messages.map((message) =>
330 message.parts.map((part) => {
331 if (part.type === "tool-call" && part.name === "updateUI") {
332 // ✅ part.input and part.output are fully typed!
333 return <div key={part.id}>Tool executed: {part.name}</div>;
334 }
335 return null;
336 })
337 )}
338 </div>
339 );
340}
341```
342
343## `createChatClientOptions(options)`
344
345Helper to create typed chat options (re-exported from `@tanstack/ai-client`).
346
347```typescript
348import {
349 createChatClientOptions,
350 fetchServerSentEvents,
351 type InferChatMessages
352} from "@tanstack/ai-client";
353import { tool1, tool2 } from "./tools";
354
355// Create typed tools array (no 'as const' needed!)
356const tools = [tool1, tool2];
357
358const chatOptions = createChatClientOptions({
359 connection: fetchServerSentEvents("/api/chat"),
360 tools,
361});
362
363type Messages = InferChatMessages<typeof chatOptions>;
364```
365
366## Types
367
368Re-exported from `@tanstack/ai-client`:
369
370- `UIMessage<TTools>` - Message type with tool type parameter
371- `MessagePart<TTools>` - Message part with tool type parameter
372- `TextPart` - Text content part
373- `ThinkingPart` - Thinking content part
374- `ToolCallPart<TTools>` - Tool call part (discriminated union)
375- `ToolResultPart` - Tool result part
376- `ChatClientOptions<TTools, TContext>` - Chat client options with typed client runtime context
377- `ConnectionAdapter` - Connection adapter interface
378- `InferChatMessages<T>` - Extract message type from options
379
380Re-exported from `@tanstack/ai`:
381
382- `toolDefinition()` - Create isomorphic tool definition
383- `ToolDefinitionInstance` - Tool definition type
384- `ClientTool` - Client tool type
385- `ServerTool` - Server tool type
386
387## Next Steps
388
389- [Getting Started](../getting-started/quick-start) - Learn the basics
390- [Tools Guide](../tools/tools) - Learn about the isomorphic tool system
391- [Client Tools](../tools/client-tools) - Learn about client-side tools