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

TypeScript
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.memo so completed messages do not re-render when new tokens arrive
  • Virtualize long lists - Use react-virtuoso or react-window for conversations with hundreds of messages
  • Debounce input - If you have auto-complete features, debounce the AI calls
  • Lazy-load markdown - Import react-markdown dynamically to reduce initial bundle size

Testing AI Components

TypeScript - __tests__/Chat.test.tsx
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

Security Essentials:
  • 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 Overview

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.