Best Practices Advanced
Shipping AI features in React apps requires attention to error handling, accessibility, performance, testing, and security. This lesson covers the essential production patterns that separate demos from real products.
Error Handling Patterns
const { messages, error, reload } = useChat({ api: '/api/chat', onError: (err) => { if (err.message.includes('429')) { showToast('Rate limited. Please wait a moment.'); } else { showToast('Something went wrong. Try again.'); } }, }); // Show error state with retry option {error && ( <div className="error-banner"> <p>Failed to get a response.</p> <button onClick={() => reload()}>Try Again</button> </div> )}
Accessibility Checklist
| Requirement | Implementation |
|---|---|
| Screen reader announcements | Use aria-live="polite" on the message container |
| Keyboard navigation | Enter to send, Shift+Enter for new line, Escape to cancel |
| Focus management | Return focus to input after message sent |
| Loading states | Use aria-busy="true" during streaming |
| Error announcements | Use role="alert" for error messages |
Performance Optimization
- Memoize message components - Use
React.memoso completed messages do not re-render when new tokens arrive - Virtualize long lists - Use
react-virtuosoorreact-windowfor conversations with hundreds of messages - Debounce input - If you have auto-complete features, debounce the AI calls
- Lazy-load markdown - Import
react-markdowndynamically to reduce initial bundle size
Testing AI Components
import { render, screen, fireEvent } from '@testing-library/react'; import { Chat } from '../components/Chat'; // Mock the useChat hook jest.mock('@ai-sdk/react', () => ({ useChat: () => ({ messages: [ { id: '1', role: 'user', content: 'Hello' }, { id: '2', role: 'assistant', content: 'Hi there!' }, ], input: '', handleInputChange: jest.fn(), handleSubmit: jest.fn(), isLoading: false, }), })); test('renders messages', () => { render(<Chat />); expect(screen.getByText('Hello')).toBeInTheDocument(); expect(screen.getByText('Hi there!')).toBeInTheDocument(); });
Security Checklist
- Never expose API keys in client-side code
- Sanitize AI-generated HTML before rendering (use react-markdown, not dangerouslySetInnerHTML)
- Validate and sanitize user inputs on the server
- Implement rate limiting per user/IP
- Add content moderation for public-facing apps
Course Complete!
Congratulations! You have completed the React + AI course. You can now build production-ready AI-powered React applications with confidence.
← Back to Course OverviewReady to Go Deeper?
Live instructor-led courses from our partners. Affiliate disclosure.
AI & ML Courses - 30% Off
Live instructor-led AI, machine learning, data science, and cloud courses for working professionals. Use code Limited30 at checkout.
EdurekaDataCamp - AI & Data Science
Hands-on Python, machine learning, and AI courses with interactive exercises and real projects.
DataCampedX - Top AI Courses
University-level AI courses from MIT, Harvard, Stanford. Earn certificates that employers recognize.
edX