Quick Example
Install
Section titled “Install”pnpm add @devscalelabs/react-sse-chatMinimal Chat Component
Section titled “Minimal Chat Component”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> );}Loading Existing Chat Data
Section titled “Loading Existing Chat Data”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.
What the Hook Handles
Section titled “What the Hook Handles”That single useChat call takes care of:
- Creating user and assistant messages
- Streaming the response via SSE
- Parsing
text_deltaevents and appending to structuredparts - Abort/stop support
- Error state management
Next Steps
Section titled “Next Steps”- Initial Messages — prepopulate the chat with existing conversation history
- Error Handling — handle errors and implement retry
- Tool Call Rendering — display tool calls and their arguments
- Markdown Rendering — render AI responses as Markdown
- Auto-scroll — scroll to the latest message during streaming
- API Reference — full list of options and return values
- Custom Event Handling — handle custom event types with generics
- Cookbook — full-stack examples