Open History to see the last commit
1---
2title: React Chat UI
3id: typed-headless-ui-react
4order: 1
5description: "Build a typed, headless React chat UI with createChatHook. Your chat options control the types of tools, parts, and interrupts."
6keywords:
7 - tanstack ai
8 - createChatHook
9 - react
10 - headless ui
11 - useAppChat
12 - ToolProps
13---
14
15Install `@tanstack/ai-react`. Import the UI factory from `@tanstack/ai-react/ui`. Call `createChatHook({ options, ...components })` once at module scope. This matches Form `createFormHook` and Table `createTableHook`: widgets register on the factory, mix onto Part / Interrupt / Input, and automatic dispatch still walks the message list.
16
17> **Deprecated.** Do not install `@tanstack/ai-react-ui`. That package re-exports this subpath until 1.0.0. See [Chat UI packages](../migration/create-ui).
18
19The factory returns `useAppChat` and `useChatContext`. Call `useAppChat()` in the screen to create the instance. Render `<chat.AppChat />`. Call `useChatContext()` inside a mapped component when it needs live chat. That value is the instance that `chat.AppChat` provides.
20
21You supply every visible component. There is no default markup, style, or copy.
22
23The factory needs a `toolsComponents` entry for every tool name in `chatOptions`. It also needs an `interruptsComponents.generic` entry for every interrupt id. `generic.fallback` is optional.
24
25Want a smaller starting point? The [chat UI recipes](./recipes/index) build one thing at a time, from a plain chat box up to per-request context.
26
27## Server
28
29```ts
30import { chat, toServerSentEventsResponse } from '@tanstack/ai'
31import { openaiText } from '@tanstack/ai-openai'
32
33export async function POST(request: Request) {
34 const json: unknown = await request.json()
35 if (typeof json !== 'object' || json === null || !('messages' in json)) {
36 return new Response('Invalid body', { status: 400 })
37 }
38 const messages = json.messages
39 const stream = chat({
40 adapter: openaiText('gpt-5.6'),
41 messages: Array.isArray(messages) ? messages : [],
42 })
43 return toServerSentEventsResponse(stream)
44}
45```
46
47## Client
48
49```tsx
50import { fetchServerSentEvents } from '@tanstack/ai-react'
51import { createChatHook } from '@tanstack/ai-react/ui'
52import { defineInterrupt, toolDefinition } from '@tanstack/ai'
53import { z } from 'zod'
54
55const getWeather = toolDefinition({
56 name: 'getWeather',
57 description: 'Look up weather',
58 inputSchema: z.object({ city: z.string() }),
59 outputSchema: z.object({ temperature: z.number() }),
60}).client()
61
62const purchaseItem = toolDefinition({
63 name: 'purchaseItem',
64 description: 'Buy an item',
65 needsApproval: true,
66 inputSchema: z.object({ item: z.string() }),
67 outputSchema: z.object({ ok: z.boolean() }),
68}).client()
69
70const choosePlan = defineInterrupt({
71 id: 'choosePlan',
72 payloadSchema: z.object({ title: z.string() }),
73 responseSchema: z.string(),
74})
75
76const chatOptions = {
77 connection: fetchServerSentEvents('/api/chat'),
78 tools: [getWeather, purchaseItem],
79 interrupts: [choosePlan],
80 outputSchema: z.object({ answer: z.string() }),
81}
82
83const { useAppChat, useChatContext } = createChatHook({
84 options: chatOptions,
85 components: {
86 layout: function Layout({ Messages, Interrupts, Input, Queue }) {
87 const chat = useChatContext()
88 if (chat.error) return <p>{chat.error.message}</p>
89 if (chat.isLoading && chat.messages.length === 0) return <p>Loading</p>
90 if (chat.messages.length === 0) return <p>Empty</p>
91 return (
92 <main>
93 <Messages />
94 <Interrupts />
95 <Queue />
96 <Input />
97 </main>
98 )
99 },
100 message: function Message({ message, Parts }) {
101 return <article data-role={message.role}><Parts /></article>
102 },
103 input: function Input() {
104 const chat = useChatContext()
105 return (
106 <form
107 onSubmit={(event) => {
108 event.preventDefault()
109 const form = event.currentTarget
110 const field = form.elements.namedItem('message')
111 if (!(field instanceof HTMLInputElement)) return
112 void chat.sendMessage(field.value)
113 field.value = ''
114 }}
115 >
116 <input name="message" />
117 <button type="submit">Send</button>
118 </form>
119 )
120 },
121 queue: function QueueItem({ item }) {
122 const label = typeof item.content === 'string' ? item.content : 'Queued'
123 return (
124 <div>
125 {label}
126 <button type="button" onClick={() => item.cancelQueued()}>
127 Cancel
128 </button>
129 </div>
130 )
131 },
132 },
133 partsComponents: {
134 text: ({ part }) => <p>{part.content}</p>,
135 structuredOutput: ({ part }) => <pre>{part.raw}</pre>,
136 toolResult: ({ part }) => <em>{String(part.content)}</em>,
137 fallback: ({ part }) => <span>{part.type}</span>,
138 },
139 toolsComponents: {
140 getWeather: ({ part, result }) => {
141 if (part.state === 'awaiting-input') return <p>Waiting</p>
142 if (part.state === 'input-streaming') return <p>Streaming input</p>
143 if (part.state === 'input-complete') return <p>{part.input?.city}</p>
144 if (part.state === 'approval-requested') return <p>Need approval</p>
145 if (part.state === 'approval-responded') return <p>Responded</p>
146 if (part.state === 'error') return <p>Error</p>
147 return (
148 <p>
149 {part.input?.city}: {String(part.output?.temperature ?? result?.content)}
150 </p>
151 )
152 },
153 purchaseItem: ({ part, interrupt }) => (
154 <div>
155 {part.input?.item}
156 {interrupt?.status === 'pending' ? (
157 <button onClick={() => interrupt.resolveInterrupt(true)}>
158 Approve
159 </button>
160 ) : null}
161 </div>
162 ),
163 },
164 interruptsComponents: {
165 generic: {
166 choosePlan: ({ interrupt }) => (
167 <button onClick={() => interrupt.resolveInterrupt('approved')}>
168 {interrupt.payload?.title ?? 'Choose plan'}
169 </button>
170 ),
171 fallback: ({ interrupt }) => <p>{interrupt.reason}</p>,
172 },
173 },
174})
175
176export function Support() {
177 const chat = useAppChat({ threadId: 'support-1' })
178 return <chat.AppChat />
179}
180
181export function Sidebar() {
182 const chat = useAppChat({ threadId: 'sidebar' })
183 return <chat.AppChat />
184}
185```
186
187`<Queue />` maps pending sends. Register `queue` on `components`. Each item has `cancelQueued()` bound, so you do not pass the id. Type a queue item with `QueueProps<typeof chatOptions>`.
188
189`layout` receives `Messages`, `Interrupts`, `Queue`, and `Input` as components. Render them as `<Messages />`, not as calls. `Input` is only on the props when the config registers an `input`, so rendering an input you never registered is a compile error instead of a silent no-op.
190
191> **List `input` before `layout`.** When `input` is an inline `function` expression written *after* `layout`, TypeScript cannot yet tell that an input is registered, and `Input` goes missing from the layout props. Putting `input` first fixes it; so does using an arrow or a named reference. If it does slip through, rendering `<Input />` without a registered `input` warns once in development rather than failing silently.
192
193## Type a component in its own file
194
195A tool map grows fast. Move a tool into its own file and type the props with `ToolProps`.
196
197`ToolProps` takes your `chatOptions` type and the tool name. Then `part.input` and `part.output` stay exact.
198
199Part components work the same way. `PartProps<typeof chatOptions, 'text'>` already has a text part. You do not check `part.type`. Use `'structuredOutput'`, `'thinking'`, `'toolResult'`, and the other keys from the `partsComponents` map. `fallback` still sees every part type.
200
201```tsx
202import { fetchServerSentEvents } from '@tanstack/ai-react'
203import { createChatHook, type PartProps, type ToolProps } from '@tanstack/ai-react/ui'
204import { toolDefinition } from '@tanstack/ai'
205import { z } from 'zod'
206
207const getWeather = toolDefinition({
208 name: 'getWeather',
209 description: 'Look up weather',
210 inputSchema: z.object({ city: z.string() }),
211 outputSchema: z.object({ temperature: z.number() }),
212}).client()
213
214const chatOptions = {
215 connection: fetchServerSentEvents('/api/chat'),
216 tools: [getWeather],
217}
218
219export function WeatherTool({
220 part,
221 result,
222}: ToolProps<typeof chatOptions, 'getWeather'>) {
223 if (part.state === 'awaiting-input') return <p>Waiting</p>
224 if (part.state === 'input-streaming') return <p>Streaming input</p>
225 if (part.state === 'error') return <p>Error</p>
226 return (
227 <p>
228 {part.input?.city}: {String(part.output?.temperature ?? result?.content)}
229 </p>
230 )
231}
232
233export function TextPart({ part }: PartProps<typeof chatOptions, 'text'>) {
234 return <p>{part.content}</p>
235}
236
237export const { useAppChat } = createChatHook({
238 options: chatOptions,
239 components: {
240 layout: ({ Messages }) => <Messages />,
241 message: ({ Parts }) => <article><Parts /></article>,
242 },
243 partsComponents: { text: TextPart, fallback: () => null },
244 toolsComponents: { getWeather: WeatherTool },
245})
246```
247
2481. Put `chatOptions` in a shared module.
2492. Import `ToolProps` or `PartProps` from `@tanstack/ai-react/ui`.
2503. Type the component with `ToolProps<typeof chatOptions, 'getWeather'>` or `PartProps<typeof chatOptions, 'text'>`.
2514. Pass that component into `tools.getWeather` or `parts.text`.
252
253For an interrupt, use `InterruptProps`. Pass a tool name or a registered interrupt id as the second type argument. Then you do not check `interrupt.kind`.
254
255- A tool approval: `InterruptProps<typeof chatOptions, 'purchaseItem'>`. Then `interrupt.toolName` is `'purchaseItem'`.
256- A registered generic interrupt: `InterruptProps<typeof chatOptions, 'choosePlan'>`. Then `interrupt.payload` and `interrupt.resolveInterrupt` match the definition.
257
258```tsx
259import { fetchServerSentEvents } from '@tanstack/ai-react'
260import { createChatHook, type InterruptProps } from '@tanstack/ai-react/ui'
261import { defineInterrupt } from '@tanstack/ai'
262import { z } from 'zod'
263
264const choosePlan = defineInterrupt({
265 id: 'choosePlan',
266 payloadSchema: z.object({ title: z.string() }),
267 responseSchema: z.string(),
268})
269
270const chatOptions = {
271 connection: fetchServerSentEvents('/api/chat'),
272 interrupts: [choosePlan],
273}
274
275export function ChoosePlan({
276 interrupt,
277}: InterruptProps<typeof chatOptions, 'choosePlan'>) {
278 return (
279 <button onClick={() => interrupt.resolveInterrupt('approved')}>
280 {interrupt.payload?.title ?? 'Choose plan'}
281 </button>
282 )
283}
284
285export const { useAppChat } = createChatHook({
286 options: chatOptions,
287 components: {
288 layout: ({ Interrupts }) => <Interrupts />,
289 message: ({ Parts }) => <article><Parts /></article>,
290 },
291 partsComponents: { fallback: () => null },
292 interruptsComponents: {
293 generic: {
294 choosePlan: ChoosePlan,
295 },
296 },
297})
298```
299
300Other prop types from the same package:
301
302- `LayoutProps`
303- `MessageProps`
304- `InputProps`
305- `QueueProps` for one queued send. `item.cancelQueued()` drops that item.
306- `PartProps` with a part key such as `'text'`
307- `InterruptProps` for tool approvals, registered generic interrupts, and `generic.fallback`. Pass a tool name or interrupt id as the second type argument.
308
309## Read chat from `useChatContext()`
310
311Mapped components do not receive `chat` as a prop. Call `useChatContext()` inside a component when it needs live chat. That call opts the component into chat re-renders. Nested children can call it too. Widgets in other files should call `createChatHookContexts()` first so they do not import the factory result (circular import).
312
313```tsx
314import { fetchServerSentEvents } from '@tanstack/ai-react'
315import { createChatHook } from '@tanstack/ai-react/ui'
316
317const chatOptions = {
318 connection: fetchServerSentEvents('/api/chat'),
319}
320
321function StatusLine() {
322 const chat = useChatContext()
323 if (chat.error) return <p>{chat.error.message}</p>
324 if (chat.isLoading) return <p>Loading</p>
325 return <p>{chat.messages.length} messages</p>
326}
327
328const { useAppChat, useChatContext } = createChatHook({
329 options: chatOptions,
330 components: {
331 layout: ({ Messages }) => (
332 <main>
333 <StatusLine />
334 <Messages />
335 </main>
336 ),
337 message: ({ Parts }) => <article><Parts /></article>,
338 },
339 partsComponents: { fallback: () => null },
340})
341
342export function ChatScreen() {
343 const chat = useAppChat()
344 return <chat.AppChat />
345}
346```
347
348Call `useChatContext()` only inside `AppChat` or `Provider`. A call outside that tree throws.
349
350`useAppChat` from `createChatHook` owns the state. `useChatContext()` only reads the instance that `chat.AppChat` provides.
351
352When a widget lives in another file, call `createChatHookContexts()` first and pass `chatContext`, `partContext`, and `interruptContext` under `context`. Then that file can import `useChatContext` from the contexts module.
353
354Part and interrupt widgets take `part` and `interrupt` as props. Type them with `PartProps`, `ToolProps`, or `InterruptProps`. Do not read those values from context.
355
356## Tool approvals: inline or list
357
358A tool with `needsApproval: true` can render its approval in two places.
359
360### Inline, next to the tool
361
362Read `interrupt` on the tool. Render the approval in that same component. Do not register `interrupts.tools` for that name. A mapped tool keeps its approval off the list.
363
364`interrupt` is already the approval for that tool name. You do not check `interrupt.kind`.
365
366```tsx
367import { fetchServerSentEvents } from '@tanstack/ai-react'
368import { createChatHook, type ToolProps } from '@tanstack/ai-react/ui'
369import { toolDefinition } from '@tanstack/ai'
370import { z } from 'zod'
371
372const purchaseItem = toolDefinition({
373 name: 'purchaseItem',
374 description: 'Buy an item',
375 needsApproval: true,
376 inputSchema: z.object({ item: z.string() }),
377 outputSchema: z.object({ ok: z.boolean() }),
378}).client()
379
380const chatOptions = {
381 connection: fetchServerSentEvents('/api/chat'),
382 tools: [purchaseItem],
383}
384
385function PurchaseItem({
386 part,
387 interrupt,
388}: ToolProps<typeof chatOptions, 'purchaseItem'>) {
389 return (
390 <div>
391 {part.input?.item}
392 {interrupt?.status === 'pending' ? (
393 <button onClick={() => interrupt.resolveInterrupt(true)}>
394 Approve
395 </button>
396 ) : null}
397 </div>
398 )
399}
400
401const { useAppChat } = createChatHook({
402 options: chatOptions,
403 components: {
404 layout: ({ Messages, Interrupts }) => (
405 <main>
406 <Messages />
407 <Interrupts />
408 </main>
409 ),
410 message: ({ Parts }) => <article><Parts /></article>,
411 },
412 partsComponents: { fallback: () => null },
413 toolsComponents: {
414 purchaseItem: PurchaseItem,
415 },
416})
417
418export function InlineApprovalChat() {
419 const chat = useAppChat()
420 return <chat.AppChat />
421}
422```
423
424To split the approval into its own file, type it with `InterruptProps<typeof chatOptions, 'purchaseItem'>`. Render that component from the tool.
425
426### List, in `<Interrupts />`
427
428Register the approval under `interrupts.tools`. That component appears in the interrupt list. Do not also render `interrupt` on the tool unless you want it in both places.
429
430```tsx
431import { fetchServerSentEvents } from '@tanstack/ai-react'
432import { createChatHook } from '@tanstack/ai-react/ui'
433import { toolDefinition } from '@tanstack/ai'
434import { z } from 'zod'
435
436const purchaseItem = toolDefinition({
437 name: 'purchaseItem',
438 description: 'Buy an item',
439 needsApproval: true,
440 inputSchema: z.object({ item: z.string() }),
441 outputSchema: z.object({ ok: z.boolean() }),
442}).client()
443
444const chatOptions = {
445 connection: fetchServerSentEvents('/api/chat'),
446 tools: [purchaseItem],
447}
448
449const { useAppChat } = createChatHook({
450 options: chatOptions,
451 components: {
452 layout: ({ Messages, Interrupts }) => (
453 <main>
454 <Messages />
455 <Interrupts />
456 </main>
457 ),
458 message: ({ Parts }) => <article><Parts /></article>,
459 },
460 partsComponents: { fallback: () => null },
461 toolsComponents: {
462 purchaseItem: ({ part }) => <div>{part.input?.item}</div>,
463 },
464 interruptsComponents: {
465 tools: {
466 purchaseItem: ({ interrupt }) => (
467 <button onClick={() => interrupt.resolveInterrupt(true)}>
468 Approve
469 </button>
470 ),
471 },
472 },
473})
474
475export function ListApprovalChat() {
476 const chat = useAppChat()
477 return <chat.AppChat />
478}
479```
480
481## Generic interrupts
482
483Generic interrupts always render in the list (`<Interrupts />` / `<UI.Interrupts>`). They never render inside a tool.
484
485Map them under `interruptsComponents.generic`:
486
487- A registered id such as `choosePlan`: the component for that definition
488- `fallback`: every other list interrupt, including an unknown generic id and an unbound interrupt this chat does not own
489
490```tsx
491import { fetchServerSentEvents } from '@tanstack/ai-react'
492import { createChatHook } from '@tanstack/ai-react/ui'
493import { defineInterrupt } from '@tanstack/ai'
494import { z } from 'zod'
495
496const choosePlan = defineInterrupt({
497 id: 'choosePlan',
498 payloadSchema: z.object({ title: z.string() }),
499 responseSchema: z.string(),
500})
501
502const chatOptions = {
503 connection: fetchServerSentEvents('/api/chat'),
504 interrupts: [choosePlan],
505}
506
507const { useAppChat } = createChatHook({
508 options: chatOptions,
509 components: {
510 layout: ({ Interrupts }) => <Interrupts />,
511 message: ({ Parts }) => <article><Parts /></article>,
512 },
513 partsComponents: { fallback: () => null },
514 interruptsComponents: {
515 generic: {
516 choosePlan: ({ interrupt }) => (
517 <button onClick={() => interrupt.resolveInterrupt('approved')}>
518 {interrupt.payload?.title ?? 'Choose plan'}
519 </button>
520 ),
521 fallback: ({ interrupt }) =>
522 interrupt.kind === 'unbound' ? (
523 <p>Paused elsewhere: {interrupt.reason}</p>
524 ) : (
525 <p>{interrupt.reason}</p>
526 ),
527 },
528 },
529})
530
531export function GenericInterruptChat() {
532 const chat = useAppChat()
533 return <chat.AppChat />
534}
535```
536
537You can mix this map with `interrupts.tools` in the same factory call.
538
539## Manual traversal
540
541`createChatUI` is the lower-level kit. Use it when you walk messages yourself. Screens still call `createChatHook`.
542
543```tsx group=manual-traversal
544import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
545import { createChatUI } from '@tanstack/ai-react/ui'
546import { toolDefinition } from '@tanstack/ai'
547import { z } from 'zod'
548
549const getWeather = toolDefinition({
550 name: 'getWeather',
551 description: 'Look up weather',
552 inputSchema: z.object({ city: z.string() }),
553 outputSchema: z.object({ temperature: z.number() }),
554}).client()
555
556const chatOptions = {
557 connection: fetchServerSentEvents('/api/chat'),
558 tools: [getWeather],
559}
560
561const UI = createChatUI(chatOptions, {
562 components: {
563 layout: ({ Messages }) => <Messages />,
564 message: ({ Parts }) => <article><Parts /></article>,
565 },
566 partsComponents: {
567 text: ({ part }) => <p>{part.content}</p>,
568 fallback: () => null,
569 },
570 toolsComponents: {
571 getWeather: ({ part }) => <p>{part.input?.city}</p>,
572 },
573})
574
575export function ManualChat() {
576 const chat = useChat(chatOptions)
577 return (
578 <UI.Provider chat={chat}>
579 <UI.Messages>
580 {(messages) =>
581 messages.map((message) => (
582 <UI.Message key={message.id} message={message}>
583 {(parts) =>
584 parts.map((part, index) => (
585 <span key={index}>{part.key}</span>
586 ))
587 }
588 </UI.Message>
589 ))
590 }
591 </UI.Messages>
592 </UI.Provider>
593 )
594}
595```
596
597Unknown runtime tool names warn once in development and render nothing. Add a `parts.fallback` for unknown part types.
598
599Automatic dispatch is the default. You can also pick a registered widget at the call site, like Form `field.TextField` and Table `cell.TextCell`:
600
601```tsx group=manual-traversal
602import type { MessageProps } from '@tanstack/ai-react/ui'
603
604function PickedWidgets({
605 message,
606}: {
607 message: MessageProps<typeof chatOptions>['message']
608}) {
609 return (
610 <UI.Message message={message}>
611 {(parts) =>
612 parts.map((part, index) => (
613 <UI.Part key={index} part={part}>
614 {(p) => (part.key === 'toolCall' ? <p.getWeather /> : <p.Render />)}
615 </UI.Part>
616 ))
617 }
618 </UI.Message>
619 )
620}
621```
622
623`p.getWeather` and `p.text` are the widgets you passed to the factory. `p.Render` walks this one part the automatic way. `UI.Input` is mixed onto the kit when you register `input`.
624
625If widgets live in other files, call `createChatHookContexts()` first and pass `chatContext`, `partContext`, and `interruptContext` under `context`. That breaks the circular import, the same way Form uses `createFormHookContexts`.
626
627See also [Solid](./solid), [Vue](./vue), [Svelte](./svelte), and [custom adapters](./custom-adapters).
628
629## Render markdown
630
631Model replies arrive as markdown. `TextPart` from `@tanstack/ai-react/ui` renders it with [TanStack Markdown](https://tanstack.com/markdown). By default, raw HTML is escaped and executable URLs are removed.
632
633```tsx
634import { TextPart } from '@tanstack/ai-react/ui'
635
636export function Reply({ content }: { content: string }) {
637 return <TextPart content={content} />
638}
639```
640
641Fenced code stays plain until you pass a `highlighter`. Build one with TanStack Highlight: [Highlight markdown code](./markdown). A custom `highlighter` returns trusted HTML. Use `createTanStackMarkdownHighlighter`, or another highlighter that escapes source text.
642
643- `highlighter`: a synchronous `CodeHighlighter`.
644- `extensions`: extra TanStack Markdown extensions. The streaming extension is always on.
645- `components`: a tag-name map with normal HTML props (`href`, `className`). `inline` and `node` are not passed.
646
647```tsx
648import { TextPart } from '@tanstack/ai-react/ui'
649
650export function Reply({ content }: { content: string }) {
651 return (
652 <TextPart
653 content={content}
654 components={{
655 a: (props) => <a {...props} target="_blank" rel="noreferrer" />,
656 }}
657 />
658 )
659}
660```
661
662If you still pass `remarkPlugins`, `rehypePlugins`, or `disableDefaultPlugins`, see [TextPart markdown](../migration/text-part-markdown).