Skip to main content

useChat Hook

The useChat hook provides access to Kapa's chat functionality, conversation state, and actions to interact with the chatbot.

Usage

import { useChat } from "@kapaai/react-sdk";

function ChatComponent() {
const {
conversation,
submitQuery,
isGeneratingAnswer,
resetConversation,
stopGeneration,
addFeedback,
} = useChat();

// Use the hook values and functions to build your UI
// ...
}

Return values

The useChat hook returns an object with the following properties:

PropertyTypeDescription
isGeneratingAnswerbooleantrue when an answer is being streamed.
isPreparingAnswerbooleantrue when the SDK is connecting to the backend.
errorstring | nullError message or null if no error occurred.
conversationConversationCurrent conversation history with all Q&A pairs.
threadIdstring | nullCurrent conversation thread ID or null if no conversation started.
submitQuery(query: string) => voidFunction to submit a new question to the AI.
resetConversation() => voidFunction to clear the conversation history.
stopGeneration() => voidFunction to abort the current generation.
addFeedback(questionAnswerId: string, reaction: Reaction, comment?: FeedbackComment) => voidFunction to send feedback for a specific Q&A pair.

Conversation object

The conversation property returned by useChat contains the complete chat history. It's an array-like object with additional helper methods for accessing question-answer pairs.

// Access a specific QA pair by ID
const specificQA = conversation.getById("qa-123");

// Get the most recent QA pair
const latestQA = conversation.getLatest();

Each QA pair contains the question, answer, sources, feedback state, and other metadata. For full details on the conversation object structure and methods, see the Conversation documentation.

Examples

Basic chat interface

import React, { useState } from "react";
import { useChat } from "@kapaai/react-sdk";

function ChatInterface() {
const [inputValue, setInputValue] = useState("");
const { conversation, submitQuery, isGeneratingAnswer, stopGeneration } =
useChat();

const handleSubmit = (e) => {
e.preventDefault();
if (inputValue.trim()) {
submitQuery(inputValue);
setInputValue("");
}
};

return (
<div className="chat-container">
<div className="messages">
{conversation.map((qa) => (
<div key={qa.id || `temp-${qa.question}`}>
<div className="user-message">{qa.question}</div>
<div className="ai-message">
{qa.answer || (isGeneratingAnswer ? "Typing..." : "")}
</div>
</div>
))}
</div>

<form onSubmit={handleSubmit}>
<input
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Ask a question..."
disabled={isGeneratingAnswer}
/>
{isGeneratingAnswer ? (
<button type="button" onClick={stopGeneration}>
Stop
</button>
) : (
<button type="submit">Send</button>
)}
</form>
</div>
);
}

Adding feedback

The addFeedback function allows users to provide thumbs-up or thumbs-down feedback on answers. Here's how it works:

addFeedback(
questionAnswerId: string,
reaction: "upvote" | "downvote",
comment?: {
incorrect?: boolean;
irrelevant?: boolean;
unaddressed?: boolean;
issue?: string;
}
) => void

It uses an optimistic update pattern, where the UI updates immediately before the API call completes. If the request fails, the UI automatically reverts to the previous state

Example:

function FeedbackButtons({ questionAnswerId }) {
const { addFeedback } = useChat();

return (
<div className="feedback-buttons">
<button onClick={() => addFeedback(questionAnswerId, "upvote")}>
👍 Helpful
</button>

{/* With detailed feedback */}
<button
onClick={() =>
addFeedback(questionAnswerId, "downvote", {
incorrect: true,
issue: "This information isn't accurate"
})
}
>
👎 Not helpful
</button>
</div>
);
}

Resetting the conversation

import { useChat } from "@kapaai/react-sdk";

function ResetButton() {
const { resetConversation } = useChat();

return (
<button onClick={resetConversation} className="reset-button">
Start New Conversation
</button>
);
}

Error handling

The error property contains details when something goes wrong:

import { useChat } from "@kapaai/react-sdk";

function ErrorDisplay() {
const { error } = useChat();

if (!error) return null;

return <div className="error-message">{error}</div>;
}

Requirements

The useChat hook must be used within a KapaProvider component.