The ModelRiver React SDK provides a first-class useModelRiver hook that manages WebSocket connections, streaming AI responses, and request lifecycle states automatically.
Installation
Bash
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.
TSX
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 // Automatically recovers request after page refresh17 });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
By setting persist: true, the SDK stores the current channel_id in localStorage. If the user refreshes the page while a request is pending, you can resume the connection.
TSX
1useEffect(() => {2 const { hasPendingRequest } = client.getState();3 if (hasPendingRequest) {4 // Call your backend to get a fresh ws_token and reconnect5 client.reconnectWithBackend();6 }7}, []);SEO Optimized AI Components in React
When building AI features in React, consider these best practices:
- Streaming UI: Use the
response.contentproperty to render partial text as it arrives for a "typing" effect. - 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.