Share useChat State Across Components
Learn how to share a chat instance across multiple components with useChat and easily reset the chat.
When building chat applications, you may want to access the same chat instance across multiple components. This allows you to display messages in one component, handle input in another, and control the chat state from anywhere in your application.
Run it locally
$ npm install aiCreate a Chat Context
First, create a context that will hold your chat instance and provide methods to interact with it.
'use client';
import React, { createContext, useContext, ReactNode, useState } from 'react';
import { Chat } from '@ai-toolkit/react';
import { DefaultChatTransport, UIMessage } from 'ai-toolkit';
interface ChatContextValue {
// replace with your custom message type
chat: Chat<UIMessage>;
clearChat: () => void;
}
const ChatContext = createContext<ChatContextValue | undefined>(undefined);
function createChat() {
return new Chat<UIMessage>({
transport: new DefaultChatTransport({
api: '/api/chat',
}),
});
}
export function ChatProvider({ children }: { children: ReactNode }) {
const [chat, setChat] = useState(() => createChat());
const clearChat = () => {
setChat(createChat());
};
return (
<ChatContext.Provider
value={{
chat,
clearChat,
}}
>
{children}
</ChatContext.Provider>
);
}
export function useSharedChatContext() {
const context = useContext(ChatContext);
if (!context) {
throw new Error('useSharedChatContext must be used within a ChatProvider');
}
return context;
}
- 1'use client';
- 2import React, { createContext, useContext, ReactNode, useState } from 'react';
- 3import { Chat } from '@ai-toolkit/react';
- 4import { DefaultChatTransport, UIMessage } from 'ai-toolkit';
- 5interface ChatContextValue {
- 6 // replace with your custom message type
- 7 chat: Chat<UIMessage>;
- 8 clearChat: () => void;
- 9}
- 10const ChatContext = createContext<ChatContextValue | undefined>(undefined);
- 11function createChat() {
- 12 return new Chat<UIMessage>({
- 13 transport: new DefaultChatTransport({
- 14 api: '/api/chat',
- 15 }),
- 16 });
- 17}
- 18export function ChatProvider({ children }: { children: ReactNode }) {
- 19 const [chat, setChat] = useState(() => createChat());
- 20 const clearChat = () => {
- 21 setChat(createChat());
- 22 };
- 23 return (
- 24 <ChatContext.Provider
- 25 value={{
- 26 chat,
- 27 clearChat,
- 28 }}
- 29 >
- 30 {children}
- 31 </ChatContext.Provider>
- 32 );
- 33}
- 34export function useSharedChatContext() {
- 35 const context = useContext(ChatContext);
- 36 if (!context) {
- 37 throw new Error('useSharedChatContext must be used within a ChatProvider');
- 38 }
- 39 return context;
- 40}
Wrap Your App with the Provider
Add the ChatProvider to your layout to make the chat context available to all child components.
import { ChatProvider } from './chat-context';
export default function Layout({ children }: { children: React.ReactNode }) {
return <ChatProvider>{children}</ChatProvider>;
}
- 1import { ChatProvider } from './chat-context';
- 2export default function Layout({ children }: { children: React.ReactNode }) {
- 3 return <ChatProvider>{children}</ChatProvider>;
- 4}
Display Messages and Clear Chat
Create a component that displays messages and provides a button to clear the chat.
'use client';
import { useChat } from '@ai-toolkit/react';
import { useSharedChatContext } from './chat-context';
import ChatInput from './chat-input';
export default function Chat() {
const { chat, clearChat } = useSharedChatContext();
const { messages } = useChat({
chat,
});
return (
<div>
<button onClick={clearChat} disabled={messages.length === 0}>
Clear Chat
</button>
{messages?.map(message => (
<div key={message.id}>
<strong>{${message.role}: }</strong>
{message.parts.map((part, index) => {
if (part.type === 'text') {
return <div key={index}>{part.text}</div>;
}
})}
</div>
))}
<ChatInput />
</div>
);
}
- 1'use client';
- 2import { useChat } from '@ai-toolkit/react';
- 3import { useSharedChatContext } from './chat-context';
- 4import ChatInput from './chat-input';
- 5export default function Chat() {
- 6 const { chat, clearChat } = useSharedChatContext();
- 7 const { messages } = useChat({
- 8 chat,
- 9 });
- 10 return (
- 11 <div>
- 12 <button onClick={clearChat} disabled={messages.length === 0}>
- 13 Clear Chat
- 14 </button>
- 15 {messages?.map(message => (
- 16 <div key={message.id}>
- 17 <strong>{`${message.role}: `}</strong>
- 18 {message.parts.map((part, index) => {
- 19 if (part.type === 'text') {
- 20 return <div key={index}>{part.text}</div>;
- 21 }
- 22 })}
- 23 </div>
- 24 ))}
- 25 <ChatInput />
- 26 </div>
- 27 );
- 28}
Handle Input in a Separate Component
Create an input component that uses the shared chat context to send messages.
import { useChat } from '@ai-toolkit/react';
import { useState } from 'react';
import { useSharedChatContext } from './chat-context';
export default function ChatInput() {
const { chat } = useSharedChatContext();
const [text, setText] = useState('');
const { status, stop, sendMessage } = useChat({ chat });
return (
<form
onSubmit={e => {
e.preventDefault();
if (text.trim() === '') return;
sendMessage({ text });
setText('');
}}
>
<input
placeholder="Say something..."
disabled={status !== 'ready'}
value={text}
onChange={e => setText(e.target.value)}
/>
{stop && (status === 'streaming' || status === 'submitted') && (
<button type="submit" onClick={stop}>
Stop
</button>
)}
</form>
);
}
- 1import { useChat } from '@ai-toolkit/react';
- 2import { useState } from 'react';
- 3import { useSharedChatContext } from './chat-context';
- 4export default function ChatInput() {
- 5 const { chat } = useSharedChatContext();
- 6 const [text, setText] = useState('');
- 7 const { status, stop, sendMessage } = useChat({ chat });
- 8 return (
- 9 <form
- 10 onSubmit={e => {
- 11 e.preventDefault();
- 12 if (text.trim() === '') return;
- 13 sendMessage({ text });
- 14 setText('');
- 15 }}
- 16 >
- 17 <input
- 18 placeholder="Say something..."
- 19 disabled={status !== 'ready'}
- 20 value={text}
- 21 onChange={e => setText(e.target.value)}
- 22 />
- 23 {stop && (status === 'streaming' || status === 'submitted') && (
- 24 <button type="submit" onClick={stop}>
- 25 Stop
- 26 </button>
- 27 )}
- 28 </form>
- 29 );
- 30}
Server
Create an API route to handle the chat messages using the AI TOOLKIT.
import { convertToModelMessages, streamText, UIMessage } from 'ai-toolkit';
export const maxDuration = 30;
export async function POST(req: Request) {
const { messages }: { messages: UIMessage[] } = await req.json();
const result = streamText({
model: 'openai/gpt-4o-mini',
messages: await convertToModelMessages(messages),
});
return result.toUIMessageStreamResponse();
}
<GithubLink link="https://github.com/khulnasoft/ai-toolkit/tree/main/examples/next-openai/app/use-chat-shared-context" />
- 1import { convertToModelMessages, streamText, UIMessage } from 'ai-toolkit';
- 2export const maxDuration = 30;
- 3export async function POST(req: Request) {
- 4 const { messages }: { messages: UIMessage[] } = await req.json();
- 5 const result = streamText({
- 6 model: 'openai/gpt-4o-mini',
- 7 messages: await convertToModelMessages(messages),
- 8 });
- 9 return result.toUIMessageStreamResponse();
- 10}