The ModelRiver React SDK provides a first-class useModelRiver hook that manages WebSocket connections, streaming AI responses, and request lifecycle states automatically.
Installation
npm install @modelriver/clientThe React adapter is included in the core @modelriver/client package.
Quick Start
The useModelRiver hook is the easiest way to integrate real-time AI into your React components.
1import React, { useState } from 'react';2import { useModelRiver } from '@modelriver/client/react';3 4export function ChatComponent() {5 const [input, setInput] = useState('');6 7 const { 8 connect, 9 response, 10 error, 11 isConnected, 12 steps,13 status 14 } = useModelRiver({15 baseUrl: 'wss://api.modelriver.com/socket',16 persist: true // The default: a pending request resumes after a reload (SDK 1.8.0+)17 });18 19 const handleSend = async () => {20 // 1. Call your own backend to start an async AI request21 const res = await fetch('/api/ai/chat', {22 method: 'POST',23 body: JSON.stringify({ prompt: input })24 });25 26 const { ws_token, channel_id } = await res.json();27 28 // 2. Connect the SDK to ModelRiver's real-time stream29 connect({ wsToken: ws_token, channelId: channel_id });30 setInput('');31 };32 33 return (34 <div className="chat-container">35 <div className="steps-progress">36 {steps.map((step) => (37 <div key={step.id} className={`step ${step.status}`}>38 {step.name}: {step.status}39 </div>40 ))}41 </div>42 43 <div className="response-area">44 {status === 'loading' && <p>AI is thinking...</p>}45 {response && (46 <div className="ai-message">47 {response.content}48 {response.data && <pre>{JSON.stringify(response.data, null, 2)}</pre>}49 </div>50 )}51 </div>52 53 <input 54 value={input} 55 onChange={(e) => setInput(e.target.value)} 56 disabled={status === 'loading'}57 />58 <button onClick={handleSend} disabled={!input || status === 'loading'}>59 Send60 </button>61 62 {error && <p className="error-message">{error}</p>}63 </div>64 );65}Key Features
useModelRiver Hook
The hook returns the following state:
isConnected: Boolean indicating if the WebSocket is connected.status:'idle' | 'loading' | 'success' | 'error'.response: The fullAIResponseobject containingcontent,data, andmeta.steps: Array ofWorkflowStepobjects (queue,process,receive,complete).error: Error message string if a request fails.connect(options): Function to initiate the connection with awsToken.
Persistence & Recovery
With persist: true (the default), the SDK stores the pending request and its single-use resume token in localStorage. The hook calls reconnect() on mount, so a request that was pending when the page reloaded resumes on its own if the reload happens within about 5 minutes. The hook also reconnects by itself after network drops; connectionState is 'reconnecting' meanwhile (SDK 1.8.0+). When the component unmounts with a request still pending, the hook closes the connection but keeps the stored request, so the next mount picks it up.
For longer gaps and ModelRiver restarts, pass getToken so the SDK can fetch a new token from your backend. Your route must check that the signed-in user owns the request; see Reconnecting.
1const { connectionState } = useModelRiver({2 // Optional: a new token from your backend for gaps longer than about 5 minutes3 getToken: async ({ channelId }) => {4 const res = await fetch(`/api/ai/requests/${channelId}/token`, { method: 'POST' });5 if (res.status === 404) return null; // the request is gone6 if (!res.ok) throw new Error(`Token route failed: ${res.status}`); // retried with backoff7 return res.json();8 },9});Streaming Tokens and Live Sessions
The adapter tracks the request's steps and final response. For token-by-token text (async requests sent with "stream": true, SDK 1.6.0+), listen to the client's stream_* events; to follow a whole conversation live (session memory, SDK 1.7.0+), use subscribeToSession. Both come from the core package and work alongside the adapter. See Streaming Tokens and Live Sessions for the details.
1import { useEffect, useState } from 'react';2import { ModelRiverClient, subscribeToSession, type SessionMessage } from '@modelriver/client';3 4// The answer as it streams in. `ticket` is your backend's /v1/ai/async response.5function useStreamedAnswer(ticket) {6 const [text, setText] = useState('');7 useEffect(() => {8 if (!ticket) return;9 const client = new ModelRiverClient({ persist: false });10 client.on('stream_delta', (_chunk, soFar) => setText(soFar));11 client.connect({12 channelId: ticket.channel_id,13 wsToken: ticket.ws_token,14 websocketUrl: ticket.websocket_url,15 websocketChannel: ticket.websocket_channel,16 });17 return () => client.disconnect();18 }, [ticket]);19 return text;20}21 22// A conversation, live: new turns (including human agents' replies) as they're stored.23function useLiveConversation(chatId: string, onMessage: (m: SessionMessage) => void) {24 useEffect(() => {25 const subscription = subscribeToSession({26 getSubscription: () => fetch(`/api/chats/${chatId}/live`, { method: 'POST' }).then((r) => r.json()),27 onMessage,28 });29 return () => subscription.close();30 }, [chatId]);31}SEO Optimized AI Components in React
When building AI features in React, consider these best practices:
- Streaming UI: Render the text from
stream_deltaevents as it arrives for a "typing" effect (see Streaming Tokens and Live Sessions);responseonly arrives once the answer is complete. - Skeleton States: Use the
stepsarray to show users exactly where the AI is in its processing pipeline (e.g., "Designing schema", "Generating content"). - Error Resilience: Always handle the
errorstate to provide users with clear retry actions. - Optimistic Updates: Clear the input immediately and show a "pending" state to make the app feel faster.
Next Steps
- Explore Workflows to configure AI models.
- Learn about Structured Outputs for JSON generation.
- Check the API Endpoints for backend implementation.