Of course! This is a classic state management problem in React/Next.js. When one component (the chat interface) needs to trigger an update in another, sibling component (the sidebar), you need a way to share state between them.
The best solution for this in Next.js (and modern React) is to use the React Context API. It allows you to create a shared "state container" that any component wrapped within its "Provider" can access and modify.
Here is a complete, step-by-step guide to implementing this for your chatbot.
Architecture Overview
- Chat Context (
ChatContext.tsx): This will be the heart of our solution. It will hold the state for chat messages and total token usage. It will also provide functions to update this state.
- Layout (
app/layout.tsx): We'll wrap our entire application with the ChatProvider here, making the shared state available to all pages and components.
- Chat Interface Component (
components/ChatInterface.tsx): This component will handle user input. When it receives a response from the LLM, it will call a function from our context to add the new messages and update the token count.
- Sidebar Component (
components/Sidebar.tsx): This component will read the state from the context. It will display the chat history and the total token usage. Because it's connected to the context, it will automatically re-render whenever the state changes.
- Main Page (
app/page.tsx): This will assemble the Sidebar and ChatInterface components.
Step 1: Create the Chat Context
First, let's create the context that will manage our shared state.
app/contexts/ChatContext.tsx
"use client"; // This must be a client component because it uses hooks (useState, createContext)
import React, { createContext, useState, useContext, ReactNode } from 'react';
// Define the shape of a single message
interface Message {
role: 'user' | 'assistant';
content: string;
}
// Define the shape of our context's state and methods
interface ChatContextType {
messages: Message[];
totalTokens: number;
isLoading: boolean;
addMessage: (message: Message, usage: { prompt_tokens: number; completion_tokens: number }) => void;
// A function to simulate the LLM call
handleUserSubmit: (prompt: string) => Promise<void>;
}
// Create the context with a default undefined value
const ChatContext = createContext<ChatContextType | undefined>(undefined);
// --- Mock LLM API Call ---
// In a real app, this would be an API route call (e.g., fetch('/api/chat', ...))
// It must return the assistant's message and the token usage.
const fetchLLMResponse = async (prompt: string): Promise<{ content: string; usage: { prompt_tokens: number; completion_tokens: number } }> => {
console.log("Simulating API call for prompt:", prompt);
// Simulate network delay
await new Promise(resolve => setTimeout(resolve, 1500));
// Simulate token usage based on text length
const prompt_tokens = Math.ceil(prompt.length / 4);
const completion_content = `This is a simulated response to your prompt: "${prompt}". The time is ${new Date().toLocaleTimeString()}.`;
const completion_tokens = Math.ceil(completion_content.length / 4);
return {
content: completion_content,
usage: {
prompt_tokens,
completion_tokens,
}
};
}
// Create the Provider component
export const ChatProvider = ({ children }: { children: ReactNode }) => {
const [messages, setMessages] = useState<Message[]>([]);
const [totalTokens, setTotalTokens] = useState<number>(0);
const [isLoading, setIsLoading] = useState<boolean>(false);
// This is the key function that updates state after the LLM responds
const addMessage = (message: Message, usage: { prompt_tokens: number; completion_tokens: number }) => {
// Add the new message to the history
setMessages(prev => [...prev, message]);
// Add the new tokens to the total
const newTokens = usage.prompt_tokens + usage.completion_tokens;
setTotalTokens(prevTotal => prevTotal + newTokens);
};
const handleUserSubmit = async (prompt: string) => {
if (!prompt.trim() || isLoading) return;
setIsLoading(true);
const userMessage: Message = { role: 'user', content: prompt };
setMessages(prev => [...prev, userMessage]); // Show user message immediately
try {
// Get response and usage from the LLM
const { content: assistantContent, usage } = await fetchLLMResponse(prompt);
const assistantMessage: Message = { role: 'assistant', content: assistantContent };
// Update state with the assistant's response AND the token usage
addMessage(assistantMessage, usage);
} catch (error) {
console.error("Failed to fetch LLM response:", error);
// Optionally add an error message to the chat
const errorMessage: Message = { role: 'assistant', content: "Sorry, I encountered an error." };
setMessages(prev => [...prev, errorMessage]);
} finally {
setIsLoading(false);
}
};
const value = {
messages,
totalTokens,
isLoading,
addMessage,
handleUserSubmit,
};
return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>;
};
// Create a custom hook for easy access to the context
export const useChat = () => {
const context = useContext(ChatContext);
if (context === undefined) {
throw new Error('useChat must be used within a ChatProvider');
}
return context;
};
Step 2: Wrap Your App in the Provider
Open your root layout and wrap the children with the ChatProvider you just created.
app/layout.tsx
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { ChatProvider } from "./contexts/ChatContext"; // Import the provider
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Next.js Chatbot",
description: "Chatbot with token usage tracking",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={inter.className}>
{/* Wrap everything in the ChatProvider */}
<ChatProvider>
{children}
</ChatProvider>
</body>
</html>
);
}
Step 3: Create the Sidebar Component
This component will use the useChat hook to read the totalTokens and messages and display them. It will automatically update when they change.
app/components/Sidebar.tsx
"use client"; // Must be a client component to use the context hook
import { useChat } from '../contexts/ChatContext';
export default function Sidebar() {
// Use the custom hook to get shared state
const { messages, totalTokens } = useChat();
return (
<aside className="w-64 bg-gray-100 p-4 border-r border-gray-300 flex flex-col">
<h2 className="text-xl font-bold mb-4">Chat App</h2>
{/* Prompt Usage Section */}
<div className="mb-6 p-3 bg-blue-100 border border-blue-300 rounded-lg">
<h3 className="font-semibold text-blue-800">Prompt Usage</h3>
<p className="text-2xl font-bold text-blue-900">{totalTokens.toLocaleString()}</p>
<p className="text-sm text-gray-600">Total Tokens Used</p>
</div>
{/* Chat History Section */}
<div className="flex-grow overflow-y-auto">
<h3 className="font-semibold mb-2">Chat History</h3>
<ul className="space-y-2">
{messages.filter(msg => msg.role === 'user').map((msg, index) => (
<li key={index} className="p-2 bg-white rounded shadow-sm text-sm truncate">
{msg.content}
</li>
))}
{messages.length === 0 && (
<p className="text-sm text-gray-500">No history yet.</p>
)}
</ul>
</div>
</aside>
);
}
Step 4: Create the Chat Interface Component
This component handles the user input and form submission. When the form is submitted, it calls handleUserSubmit from our context.
app/components/ChatInterface.tsx
"use client"; // Must be a client component for form handling and hooks
import { useState, FormEvent, useRef, useEffect } from 'react';
import { useChat } from '../contexts/ChatContext';
export default function ChatInterface() {
const [input, setInput] = useState('');
const { messages, isLoading, handleUserSubmit } = useChat();
const messagesEndRef = useRef<HTMLDivElement | null>(null);
// Scroll to the bottom of the chat on new messages
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages]);
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
await handleUserSubmit(input);
setInput(''); // Clear input after submission
};
return (
<main className="flex-1 flex flex-col h-screen">
{/* Message Display Area */}
<div className="flex-1 overflow-y-auto p-6 space-y-4">
{messages.map((msg, index) => (
<div key={index} className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
<div className={`max-w-xl p-3 rounded-lg ${msg.role === 'user' ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-800'}`}>
<p>{msg.content}</p>
</div>
</div>
))}
{isLoading && (
<div className="flex justify-start">
<div className="max-w-xl p-3 rounded-lg bg-gray-200 text-gray-800">
<p className="animate-pulse">Thinking...</p>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
{/* Input Form */}
<div className="p-4 bg-white border-t border-gray-200">
<form onSubmit={handleSubmit} className="flex space-x-2">
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Enter your prompt..."
className="flex-1 p-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
disabled={isLoading}
/>
<button
type="submit"
disabled={isLoading || !input.trim()}
className="px-4 py-2 bg-blue-500 text-white rounded-lg disabled:bg-gray-400 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
{isLoading ? "Saving..." : "Send"}
</button>
</form>
</div>
</main>
);
}
Step 5: Assemble the Page
Finally, create your main page file to put the two components together.
app/page.tsx
import Sidebar from "./components/Sidebar";
import ChatInterface from "./components/ChatInterface";
export default function Home() {
return (
<div className="flex h-screen bg-gray-50">
<Sidebar />
<ChatInterface />
</div>
);
}
How It Works: The Flow
- User Action: The user types a prompt in the
ChatInterface and clicks "Send".
- Trigger: The
onSubmit handler in ChatInterface calls the handleUserSubmit function, which it gets from the useChat() hook.
- API Call & State Update:
- The
handleUserSubmit function (defined in ChatContext.tsx) adds the user's message to the state immediately for a fast UI response.
- It then calls your LLM API (here, a mocked function).
- When the API returns the assistant's response and the token usage, it calls the internal
addMessage function.
- Centralized State Change: The
addMessage function updates both the messages array and the totalTokens number within the ChatProvider's state.
- Automatic Re-render: Because React's state has changed, React automatically re-renders any component that consumes this state.
- The
Sidebar component uses useChat() to get totalTokens. It sees the new value and re-renders the "Prompt Usage" section.
- The
ChatInterface component uses useChat() to get messages. It sees the new assistant message and re-renders the chat log.
This architecture is clean, scalable, and the standard way to handle cross-component state management in modern Next.js applications.