Open History to see the last commit
1---
2title: Preact Chat UI
3id: typed-headless-ui-preact
4order: 5
5description: "Render a streaming chat in Preact with your own components. createChatHook types every tool, part, and interrupt, with the same API as React."
6keywords:
7 - tanstack ai
8 - createChatHook
9 - preact
10 - headless ui
11 - ToolProps
12---
13
14`createChatHook` from `@tanstack/ai-preact/ui` binds your chat options and components once. Tool calls and approvals stay typed.
15
16Each screen then renders the chat with one hook call. The API is the same as [React](./react). Widgets are Preact components. You supply every visible component. There is no default markup or style.
17
18## Quick setup
19
201. Install the packages:
21
22<!-- ::start:tabs variant="package-manager" mode="install" -->
23
24preact: @tanstack/ai @tanstack/ai-preact @tanstack/ai-openai
25
26<!-- ::end:tabs -->
27
282. Put `OPENAI_API_KEY` in your server environment. Then add a `POST` route at `/api/chat`:
29
30```ts
31import {
32 chat,
33 chatParamsFromRequest,
34 toServerSentEventsResponse,
35} from '@tanstack/ai'
36import { openaiText } from '@tanstack/ai-openai'
37
38export async function POST(request: Request) {
39 const { messages, threadId, runId } = await chatParamsFromRequest(request)
40
41 const stream = chat({
42 adapter: openaiText('gpt-6.1-sol'),
43 messages,
44 threadId,
45 runId,
46 })
47
48 return toServerSentEventsResponse(stream)
49}
50```
51
523. Create `src/chat.tsx`:
53
54```tsx
55import { fetchServerSentEvents } from '@tanstack/ai-preact'
56import { createChatHook } from '@tanstack/ai-preact/ui'
57
58const chatOptions = {
59 connection: fetchServerSentEvents('/api/chat'),
60}
61
62const { useAppChat } = createChatHook({
63 options: chatOptions,
64 components: {
65 layout: (props) => (
66 <section>
67 <props.Messages />
68 </section>
69 ),
70 message: (props) => (
71 <article data-role={props.message.role}>
72 <props.Parts />
73 </article>
74 ),
75 },
76 partsComponents: {
77 text: (props) => <p>{props.part.content}</p>,
78 fallback: () => null,
79 },
80})
81
82export function ChatScreen() {
83 const chat = useAppChat({ threadId: 'support-chat' })
84
85 return (
86 <main>
87 <chat.AppChat />
88 <form
89 onSubmit={(event) => {
90 event.preventDefault()
91 const field = event.currentTarget.elements.namedItem('message')
92 if (!(field instanceof HTMLInputElement)) return
93 const text = field.value.trim()
94 if (!text) return
95 field.value = ''
96 void chat.sendMessage(text)
97 }}
98 >
99 <input name="message" />
100 <button type="submit">Send</button>
101 </form>
102 </main>
103 )
104}
105```
106
1074. Render `<ChatScreen />` and send a message.
108
109The reply streams into the page as the model writes it.
110
111## How it works
112
113- `createChatHook` runs once, at module scope. It binds `chatOptions` to your components.
114- `useAppChat({ threadId })` creates one chat instance. `chat.AppChat` renders that instance with your components.
115- `layout` places the message list. `message` wraps one message. `Parts` picks a component for each part of that message.
116- `partsComponents.text` renders text. `fallback` catches every part type that you did not register.
117
118## Next steps
119
120Each step adds one thing to the quick setup. The [chat UI recipes](./recipes/index) have the full file for each one. The recipes use React, and the code is the same in Preact.
121
122### Render a tool
123
124Add the tool to `tools` in `chatOptions`. Then register a component under the tool name in `toolsComponents`. `part.input` and `part.output` are typed from the tool schemas.
125
126```tsx ignore
127toolsComponents: {
128 getWeather: (props) =>
129 props.part.state === 'complete' ? (
130 <p>
131 {props.part.input?.city}: {props.part.output?.temperature}
132 </p>
133 ) : (
134 <p>Looking up weather</p>
135 ),
136},
137```
138
139The factory needs one entry for every tool in `chatOptions`. Full example: [Make a tool look right](./recipes/format-a-tool).
140
141### Ask before a tool runs
142
143Set `needsApproval: true` on the tool. The tool component then gets an `interrupt` prop:
144
145```tsx ignore
146toolsComponents: {
147 deleteFile: (props) =>
148 props.interrupt?.status === 'pending' ? (
149 <button onClick={() => props.interrupt?.resolveInterrupt(true)}>
150 Delete {props.part.input?.path}
151 </button>
152 ) : (
153 <p>{props.part.input?.path}</p>
154 ),
155},
156```
157
158`resolveInterrupt(true)` approves. `resolveInterrupt(false)` denies. Full example: [Ask before a tool runs](./recipes/tool-approval).
159
160### Ask the user your own question
161
162Define the question with `defineInterrupt`. Add it to `interrupts` in `chatOptions`. Register a component under its id in `interruptsComponents.generic`, and render `props.Interrupts` in the layout:
163
164```tsx ignore
165const choosePlan = defineInterrupt({
166 id: 'choosePlan',
167 payloadSchema: z.object({ title: z.string() }),
168 responseSchema: z.string(),
169})
170
171// In createChatHook:
172interruptsComponents: {
173 generic: {
174 choosePlan: (props) => (
175 <button onClick={() => props.interrupt.resolveInterrupt('pro')}>
176 {props.interrupt.payload?.title}
177 </button>
178 ),
179 fallback: (props) => <p>{props.interrupt.reason}</p>,
180 },
181},
182```
183
184The factory needs one entry for every interrupt id in `chatOptions`. Full example: [Ask the user your own question](./recipes/custom-interrupt).
185
186### Read chat state inside a widget
187
188Mapped components do not get `chat` as a prop. Call `useChatContext()` inside the widget. This also moves the composer into the layout: register it as `input`, then render `props.Input`.
189
190```tsx
191import { fetchServerSentEvents } from '@tanstack/ai-preact'
192import { createChatHook } from '@tanstack/ai-preact/ui'
193
194const chatOptions = {
195 connection: fetchServerSentEvents('/api/chat'),
196}
197
198const { useAppChat, useChatContext } = createChatHook({
199 options: chatOptions,
200 components: {
201 input: () => {
202 const chat = useChatContext()
203 return (
204 <form
205 onSubmit={(event) => {
206 event.preventDefault()
207 const field = event.currentTarget.elements.namedItem('message')
208 if (!(field instanceof HTMLInputElement)) return
209 const text = field.value.trim()
210 if (!text) return
211 field.value = ''
212 void chat.sendMessage(text)
213 }}
214 >
215 <input name="message" disabled={chat.isLoading} />
216 <button type="submit">Send</button>
217 </form>
218 )
219 },
220 layout: (props) => (
221 <main>
222 <props.Messages />
223 <props.Input />
224 </main>
225 ),
226 message: (props) => (
227 <article>
228 <props.Parts />
229 </article>
230 ),
231 },
232 partsComponents: {
233 text: (props) => <p>{props.part.content}</p>,
234 fallback: () => null,
235 },
236})
237
238export function ChatScreen() {
239 const chat = useAppChat({ threadId: 'support-chat' })
240 return <chat.AppChat />
241}
242```
243
244Call `useChatContext()` only inside `chat.AppChat`. A call outside that tree throws. For hooks inside a widget, import them from `preact/hooks`.
245
246### Render markdown
247
248`@tanstack/ai-preact/ui` has no `TextPart` component. Render `part.content` in your own text part, with the markdown library of your choice.
249
250### Type a widget in its own file
251
252Move a widget to its own file and type its props with `ToolProps`, `PartProps`, or `InterruptProps`. Pass `typeof chatOptions` and a name:
253
254```tsx
255import { fetchServerSentEvents } from '@tanstack/ai-preact'
256import { createChatHook, type ToolProps } from '@tanstack/ai-preact/ui'
257import { toolDefinition } from '@tanstack/ai'
258import { z } from 'zod'
259
260const getWeather = toolDefinition({
261 name: 'getWeather',
262 description: 'Look up weather',
263 inputSchema: z.object({ city: z.string() }),
264 outputSchema: z.object({ temperature: z.number() }),
265}).client()
266
267const chatOptions = {
268 connection: fetchServerSentEvents('/api/chat'),
269 tools: [getWeather],
270}
271
272export function WeatherTool(
273 props: ToolProps<typeof chatOptions, 'getWeather'>,
274) {
275 return <strong>{props.part.input?.city}</strong>
276}
277
278export const { useAppChat } = createChatHook({
279 options: chatOptions,
280 components: {
281 layout: (props) => <props.Messages />,
282 message: (props) => (
283 <article>
284 <props.Parts />
285 </article>
286 ),
287 },
288 partsComponents: { fallback: () => null },
289 toolsComponents: { getWeather: WeatherTool },
290})
291```
292
293Put `chatOptions` in a shared module so every widget file can import its type.
294
295You now have a typed chat UI in Preact. Each widget is your own component.
296
297## Advanced
298
299### Slots and props
300
301The config keys, part keys, and prop types are the same as in React. See [Every widget slot](./react#every-widget-slot). In Preact, `layout` gets `Messages`, `Interrupts`, and `Queue`, plus `Input` when you register `input`.
302
303`useAppChat()` takes per-instance options: `threadId` (required), `initialMessages`, `live`, and `forwardedProps`.
304
305### Approvals, interrupts, and the queue
306
307These work the same as in React:
308
309- [Approval next to the tool, or in the list](./react#approval-next-to-the-tool-or-in-the-list)
310- [Generic interrupts and `fallback`](./react#generic-interrupts-and-fallback)
311- [Show queued messages](./react#show-queued-messages)
312- [List `input` before `layout`](./react#list-input-before-layout)
313- [Widgets in other files](./react#widgets-in-other-files), with `createChatHookContexts` from `@tanstack/ai-preact/ui`