Skip to content
Docs
useChat

useChat

useChat(options: UseChatOptions): ChatHelpers

useChat is a utility to allow you to easily create a conversational user interface for your chatbot application. It enables the streaming of chat messages from your AI provider, manages the state for chat input, and updates the UI automatically as new messages are received.

To use useChat in React projects, you can import it from the ai/react subpath. Below is a usage example demonstrating a basic chat interface:

app/chat.tsx
'use client';
 
import { useChat } from 'ai/react';
 
export default function Chat() {
  const { messages, input, handleInputChange, handleSubmit } = useChat();
 
  return (
    <div>
      {messages.map(m => (
        <div key={m.id}>
          {m.role === 'user' ? 'User: ' : 'AI: '}
          {m.content}
        </div>
      ))}
 
      <form onSubmit={handleSubmit}>
        <label>
          Say something...
          <input value={input} onChange={handleInputChange} />
        </label>
        <button type="submit">Send</button>
      </form>
    </div>
  );
}

After submitting a message, the useChat hook will automatically append a user message to the chat history and trigger an API call to the configured endpoint. The response will be streamed to the chat history and returned by the hook as messages. Whenever a new chunk of streamed messages is received, the hook will automatically update the messages state and trigger a re-render.

This enables a seamless chat experience where the user can see the AI response as soon as it is available, without having to wait for the entire response to be received.

UseChatOptions

Options passed to useChat:

OptionTypeDescription
apistring = '/api/chat'The API endpoint that accepts a `{ messages: Message[] }` object and returns a stream of tokens of the AI chat response. Defaults to `/api/chat`.
idstringAn unique identifier for the chat. If not provided, a random one will be generated. When provided, the `useChat` hook with the same `id` will have shared states across components. This is useful when you have multiple components showing the same chat stream
initialInputstring = ''An optional string of initial prompt input
initialMessagesMessages[] = []An optional array of initial chat messages
onResponse(res: Response) => voidAn optional callback that will be called with the response from the API endpoint. Useful for throwing customized errors or logging
onFinish(message: Message) => voidAn optional callback that will be called when the chat stream ends
onError(err: Error) => voidAn optional callback that will be called when the chat stream encounters an error
headersRecord<string, string> | HeadersAn optional object of headers to be passed to the API endpoint
bodyanyAn optional, extra body object to be passed to the API endpoint in addition to the `messages` array
credentials"omit" | "same-origin" | "include"An optional literal that sets the mode of credentials to be used on the request. Defaults to "same-origin".
sendExtraMessageFieldsbooleanAn optional boolean that determines whether to send extra fields you've added to `messages`. Defaults to `false` and only the `content` and `role` fields will be sent to the API endpoint.

ChatHelpers

The useChat hook returns an object containing several helper methods and variables to manage the chat state:

OptionTypeDescription
messagesMessage[]The current array of chat messages.
errorError | undefinedAn error object returned by SWR, if any.
append(message: Message | CreateMessage, chatRequestOptions: { options: { headers, body } }) => Promise<string | undefined>Function to append a message to the chat, triggering an API call for the AI response. It returns a promise that resolves to full response message content when the API call is successfully finished, or throws an error when the API call fails.
reload() => Promise<string | undefined>Function to reload the last AI chat response for the given chat history. If the last message isn't from the assistant, it will request the API to generate a new response.
stop() => voidFunction to abort the current API request.
setMessages(messages: Message[]) => voidFunction to update the `messages` state locally without triggering an API call.
inputstringThe current value of the input field.
setInputReact.Dispatch<React.SetStateAction<string>>Function to update the `input` value.
handleInputChange(e: any) => voidHandler for the `onChange` event of the input field to control the input's value.
handleSubmit(e: React.FormEvent<HTMLFormElement>) => voidForm submission handler that automatically resets the input field and appends a user message.
isLoadingbooleanBoolean flag indicating whether a request is currently in progress.
dataJSONValue[]Data returned from experimental_StreamData