liveBook · Manning

useChat

As explained in Build AI-Enhanced Web Apps

useChat is a Vercel AI SDK React hook that manages conversational messages, input state, submissions, and streamed responses.

useChat is a Vercel AI SDK React hook for building conversational interfaces. It manages the message list and input, submits chat requests, and updates the UI as responses stream in. This replaces much of the state and streaming logic a custom chat hook would otherwise need. section 3.2.2 section 3.2.3

Connect a chat form

Import useChat from 'ai/react' and call useChat({ api: '/api' }). Render messages, bind an input’s value and onChange to input and handleInputChange, and attach handleSubmit to the form. The hook also exposes isLoading for the streaming chat interface. section 3.2.2 section 3.2.3

The API route supplies the other half of the integration: read messages from the request, pass them to streamText with a selected model, and return a streaming response. Delivering chunks as they arrive lets the conversation update without waiting for the complete answer. section 3.2.3

Send model selections

Keep the selected provider and model in React state, then pass body: { provider, model } to useChat alongside api. The route reads those values, selects a supported model, and streams its response. Because useChat maintains one message list, users can change providers while retaining conversation context. section 3.3.3

Listing 3.6 useChat example
import { useChat } from 'ai/react';    #1

export default function Chat() {
  const { messages, input, handleInputChange, handleSubmit} =
    useChat({ api: '/api' });    #2

return (
    <div>
      <Messages data={messages} />.   #3
      <form onSubmit={handleSubmit}>
        <input
          value={input}
          placeholder="Ask me something..."
          onChange={handleInputChange}
        />
      </form>
    </div>
 )
  }

A minimal component shows how messages, input, handleInputChange, and handleSubmit connect to a chat form. section 3.2.2

How Build AI-Enhanced Web Apps covers it

How deep it goes
Works through form bindings, a streaming API route, and provider selection without detailing the hook’s internals.
Examples
Shows a bound chat form, a streaming route, and provider and model controls for one conversation.
What it assumes
Assumes familiarity with React components and API routes while showing how to wire the AI SDK into both.
What you can do after
Apply it via the Vercel AI SDK to replace custom chat state handling and display streamed responses.
How it connects
Connects React state, API routes, streamText, streaming responses, and AI provider selection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build AI-Enhanced Web Apps. The section links point to the parts of the book it draws on.