Share useChat State Across Components

Learn how to share a chat instance across multiple components with useChat and easily reset the chat.

3 min readnextuseChatcontextView source

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 ai

Create 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;

}

app/chat-context.tsx
tsx
  1. 1'use client';
  2. 2import React, { createContext, useContext, ReactNode, useState } from 'react';
  3. 3import { Chat } from '@ai-toolkit/react';
  4. 4import { DefaultChatTransport, UIMessage } from 'ai-toolkit';
  5. 5interface ChatContextValue {
  6. 6 // replace with your custom message type
  7. 7 chat: Chat<UIMessage>;
  8. 8 clearChat: () => void;
  9. 9}
  10. 10const ChatContext = createContext<ChatContextValue | undefined>(undefined);
  11. 11function createChat() {
  12. 12 return new Chat<UIMessage>({
  13. 13 transport: new DefaultChatTransport({
  14. 14 api: '/api/chat',
  15. 15 }),
  16. 16 });
  17. 17}
  18. 18export function ChatProvider({ children }: { children: ReactNode }) {
  19. 19 const [chat, setChat] = useState(() => createChat());
  20. 20 const clearChat = () => {
  21. 21 setChat(createChat());
  22. 22 };
  23. 23 return (
  24. 24 <ChatContext.Provider
  25. 25 value={{
  26. 26 chat,
  27. 27 clearChat,
  28. 28 }}
  29. 29 >
  30. 30 {children}
  31. 31 </ChatContext.Provider>
  32. 32 );
  33. 33}
  34. 34export function useSharedChatContext() {
  35. 35 const context = useContext(ChatContext);
  36. 36 if (!context) {
  37. 37 throw new Error('useSharedChatContext must be used within a ChatProvider');
  38. 38 }
  39. 39 return context;
  40. 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>;

}

app/layout.tsx
tsx
  1. 1import { ChatProvider } from './chat-context';
  2. 2export default function Layout({ children }: { children: React.ReactNode }) {
  3. 3 return <ChatProvider>{children}</ChatProvider>;
  4. 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>

);

}

app/page.tsx
tsx
  1. 1'use client';
  2. 2import { useChat } from '@ai-toolkit/react';
  3. 3import { useSharedChatContext } from './chat-context';
  4. 4import ChatInput from './chat-input';
  5. 5export default function Chat() {
  6. 6 const { chat, clearChat } = useSharedChatContext();
  7. 7 const { messages } = useChat({
  8. 8 chat,
  9. 9 });
  10. 10 return (
  11. 11 <div>
  12. 12 <button onClick={clearChat} disabled={messages.length === 0}>
  13. 13 Clear Chat
  14. 14 </button>
  15. 15 {messages?.map(message => (
  16. 16 <div key={message.id}>
  17. 17 <strong>{`${message.role}: `}</strong>
  18. 18 {message.parts.map((part, index) => {
  19. 19 if (part.type === 'text') {
  20. 20 return <div key={index}>{part.text}</div>;
  21. 21 }
  22. 22 })}
  23. 23 </div>
  24. 24 ))}
  25. 25 <ChatInput />
  26. 26 </div>
  27. 27 );
  28. 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>

);

}

app/chat-input.tsx
tsx
  1. 1import { useChat } from '@ai-toolkit/react';
  2. 2import { useState } from 'react';
  3. 3import { useSharedChatContext } from './chat-context';
  4. 4export default function ChatInput() {
  5. 5 const { chat } = useSharedChatContext();
  6. 6 const [text, setText] = useState('');
  7. 7 const { status, stop, sendMessage } = useChat({ chat });
  8. 8 return (
  9. 9 <form
  10. 10 onSubmit={e => {
  11. 11 e.preventDefault();
  12. 12 if (text.trim() === '') return;
  13. 13 sendMessage({ text });
  14. 14 setText('');
  15. 15 }}
  16. 16 >
  17. 17 <input
  18. 18 placeholder="Say something..."
  19. 19 disabled={status !== 'ready'}
  20. 20 value={text}
  21. 21 onChange={e => setText(e.target.value)}
  22. 22 />
  23. 23 {stop && (status === 'streaming' || status === 'submitted') && (
  24. 24 <button type="submit" onClick={stop}>
  25. 25 Stop
  26. 26 </button>
  27. 27 )}
  28. 28 </form>
  29. 29 );
  30. 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" />

app/api/chat/route.ts
tsx
  1. 1import { convertToModelMessages, streamText, UIMessage } from 'ai-toolkit';
  2. 2export const maxDuration = 30;
  3. 3export async function POST(req: Request) {
  4. 4 const { messages }: { messages: UIMessage[] } = await req.json();
  5. 5 const result = streamText({
  6. 6 model: 'openai/gpt-4o-mini',
  7. 7 messages: await convertToModelMessages(messages),
  8. 8 });
  9. 9 return result.toUIMessageStreamResponse();
  10. 10}