Skip to content

Quick Example

Terminal window
pnpm add @devscalelabs/react-sse-chat
import { useChat } from "@devscalelabs/react-sse-chat";
function Chat() {
const { messages, isLoading, sendMessage, stop } = useChat({
api: "http://localhost:8000/chat/",
body: { session_id: "3" },
});
return (
<div>
{messages.map((msg) => (
<div key={msg.id}>
<strong>{msg.role}:</strong>
{msg.parts.map((part, i) => {
switch (part.type) {
case "text":
return <span key={i}>{part.text}</span>;
default:
return null;
}
})}
</div>
))}
{isLoading && <button onClick={stop}>Stop</button>}
<form
onSubmit={(e) => {
e.preventDefault();
const input = e.currentTarget.elements.namedItem("message") as HTMLInputElement;
sendMessage(input.value);
input.value = "";
}}
>
<input name="message" placeholder="Type a message..." />
<button type="submit" disabled={isLoading}>Send</button>
</form>
</div>
);
}

Use initialMessages to prepopulate the chat with existing conversation history:

const savedMessages = await fetchChatHistory(sessionId);
const { messages, sendMessage } = useChat({
api: "/chat",
initialMessages: savedMessages,
});

This is optional — if omitted, the chat starts empty.

That single useChat call takes care of:

  • Creating user and assistant messages
  • Streaming the response via SSE
  • Parsing text_delta events and appending to structured parts
  • Abort/stop support
  • Error state management